Merge K Sorted Lists

50 min · mergeKLists()

Several sorted result feeds arrive at once. You need one clean timeline, and rereading all the values after every choice won't survive the largest import.

Given lists, an array of integer arrays, merge every value into one sorted array and return it. Each inner array is already sorted in non-decreasing order.

Non-decreasing means each value is at least the value before it, so duplicates are allowed.

A few ground rules:

  • An inner array may be empty, and lists itself may be empty.
  • Keep every occurrence of every value, including duplicates across different arrays.
  • The returned array must be sorted in non-decreasing order.

Constraints

  • 0 <= lists.length <= 10_000
  • 0 <= lists[i].length
  • The total number of values across all inner arrays is at most 100_000.
  • Every lists[i] is sorted in non-decreasing order.
  • -1_000_000_000 <= lists[i][j] <= 1_000_000_000

Hints

Start with the honest baseline

You can collect every value and sort the result. That works, but it throws away the ordering each input array already gives you.

Only k values are ready

At any moment, the next answer must be one of the current first unused values from the non-empty arrays. How could you retrieve the smallest of those candidates?

Remember where a value came from

Put each current head in a min-heap along with its array index and position. After removing one, advance only that array and add its next value.

Follow-up

Can you explain why the heap never needs more than one entry per input array, even when the arrays together contain 100,000 values?

Visible cases

Examples

Example 1

ready
Input
lists = [
  [
    1,
    4,
    5
  ],
  [
    1,
    3,
    4
  ],
  [
    2,
    6
  ]
]
Expected
[
  1,
  1,
  2,
  3,
  4,
  4,
  5,
  6
]
Why
the three sorted streams interleave into one ordered result

Example 2

ready
Input
lists = []
Expected
[]
Why
no input arrays means no values to merge

Example 3

ready
Input
lists = [
  []
]
Expected
[]
Why
an empty inner array contributes nothing

Interview signal

Asked at

AmazonGoogleMicrosoftUber
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite