Merge K Sorted Arrays
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
You are given a list of k arrays, where each individual array is already sorted in non-decreasing order. The arrays may have different lengths, and some of them may be empty.
Combine every element from all of the arrays into a single array that is also sorted in non-decreasing order, and return it.
Duplicate values are allowed and must all be preserved in the output. If every input array is empty (or the list of arrays itself is empty), return an empty array.
Aim for a solution that is efficient even when there are many arrays. A min-heap that tracks the current smallest unconsumed element across all arrays lets you produce the merged result in O(N log k) time, where N is the total number of elements and k is the number of arrays.
Examples
Constraints
- `0 <= k <= 10^4` (k is the number of arrays)
- `0 <= arrays[i].length`
- The total number of elements across all arrays does not exceed `10^5`
- `-10^9 <= arrays[i][j] <= 10^9`
- Each `arrays[i]` is sorted in non-decreasing order
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.