← Questions
Merge k sorted arrays
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's coding round, last asked Oct 2025. It tests heaps and merging.
You get k arrays of integers, each sorted in non-decreasing order, with N elements in total. Merge them into one sorted array. Scanning every array's head at each step costs O(N·k), which is too slow when k is large; aim for something asymptotically better.
Interface
Unless you agree on a different interface with the interviewer, assume:
merge_k_sorted(arrays: list[list[int]]) -> list[int]
Example
[[1, 4, 9], [2, 6], [0, 3, 7, 8]] -> [0, 1, 2, 3, 4, 6, 7, 8, 9]
[] -> []
[[], [5], []] -> [5]
Constraints
-
0 <= k <= 10^5; any array may be empty. -
0 <= N <= 10^6. - Values fit in a 32-bit signed integer.
Clarifying questions
- Can arrays be empty, and can there be no arrays at all?
- Must the merge be stable when values are equal?
- Do the arrays fit in memory, or are they streams or files?
What a strong answer covers
- A min-heap holding
(value, array_index, element_index)for the front of each non-empty array: pop the smallest, append it, push the next element from the same array. - O(N log k) time and O(k) extra space, beyond the output.
- The alternative: merge pairs of arrays in rounds, like merge sort, also O(N log k); why merging one array at a time into the result is O(N·k).
- Edge cases: empty arrays, all arrays empty, duplicates across arrays.
- Tests with uneven lengths and with
k = 1.
Follow-ups
- The arrays are sorted files too large for memory: an external merge with buffered readers.
- Return only the
m-th smallest element across all arrays. - Merge
ksorted linked lists in place.
Where it's asked
- Microsoft · Coding · Last asked Oct 202560 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent
What it tests
heaps · merging
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
