KatInterview

Combine Several Pre-Sorted Lists Into One Sorted List

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapmergek-way-merge

Last updated

Tests merging K nondecreasing integer lists into a single sorted list, preserving duplicates and handling empty lists, using a heap or pairwise merging.

You are given a list called lists. Each element of lists is itself a list of integers, already arranged in nondecreasing (ascending, ties allowed) order.

Write a function that produces one new list containing every integer from every inner list, arranged in nondecreasing order.

Rules

  • Every occurrence of a value must appear in the output. If a value shows up three times across the inputs, it appears three times in the result.
  • Inner lists may be empty, and they may have different lengths.
  • lists itself may be empty, in which case the result is an empty list.
  • Values may be negative, zero, or positive.
  • Return a freshly built list. Do not modify the input lists.

The result is simply the sorted multiset union of all the inputs, so there is only one correct output for any given input. Aim to exploit the fact that each inner list is already sorted, rather than throwing everything into one list and sorting it from scratch.

Constraints

  • 0 <= len(lists)
  • Each inner list is sorted in nondecreasing order and may be empty.
  • Elements are integers (negatives and duplicates allowed).
  • The total number of elements across all inner lists fits comfortably in memory.

Examples

Example 1

Input: combine_sorted_lists([[1, 3, 5], [2, 4, 6]])

Output: [1, 2, 3, 4, 5, 6]

Example 2

Input: combine_sorted_lists([[-5, -1, 2], [0, 2, 9, 10]])

Output: [-5, -1, 0, 2, 2, 9, 10]

Example 3

Input: combine_sorted_lists([[], [-3, -3], [], [1, 4, 4]])

Output: [-3, -3, 1, 4, 4]

Example 4

Input: combine_sorted_lists([[1, 2, 2, 7], [1, 1, 3], [-2, 8]])

Output: [-2, 1, 1, 1, 2, 2, 3, 7, 8]

Hints

Hint 1

At any moment, the smallest value not yet output must be the first unused element of one of the inner lists.

Hint 2

Keep a min-heap holding one candidate per non-empty inner list. Store the value together with the list index and the position so you know where to continue from.

Hint 3

After popping the smallest candidate, push the next element from the same inner list if there is one. Skip empty inner lists when building the initial heap.