Maintained by Vikas Dulgunde, software engineer
You are given a list of arrays, where each inner array is itself sorted in non-decreasing order. Your job is to fold all of these inputs together into one array that is also sorted in non-decreasing order and holds every value from every input.
Duplicates are kept, not removed. If the same number appears in three different arrays, it appears three times in the result. Values can be negative, and the inputs can vary widely in length.
The key signal is that each input is pre-sorted. A naive approach ignores that and just sorts everything from scratch, but the better solutions exploit the existing order so you never re-compare elements that are already known to be in sequence.
The three arrays interleave perfectly. Repeatedly taking the smallest available front element gives 1 from the first, 2 from the second, 3 from the third, and so on.
These two ranges do not overlap. The first array is fully drained before any element of the second is smaller than what remains, so they simply concatenate in order.
Negatives sort ahead of positives, and the shared value 0 appears in two arrays so it shows up twice in the merged output.
Visible test cases
At any moment, the next value in the merged output is the smallest among the current front elements of the arrays that still have elements left. You never need to look past the front of each array.
You want a structure that hands you the minimum of up to k candidates quickly and lets you replace that minimum with the next element from the same array. A min-heap does exactly this in logarithmic time per operation.
Store a small record in the heap for each candidate: the value plus which array it came from and its position in that array. When you pop the smallest, push the next element from that same array if one exists.
Ignore the existing order, dump every element into one flat array, and run a general comparison sort over the whole thing.
Keep only the current front element of each array in a min-heap. The heap root is always the next value to emit, and after emitting it you replace it with the successor from the same array.