KatInterview

Combine Multiple Sorted Lists into a Single Sorted Sequence

Heaps, Sorting & SearchAuto-graded · 19 test cases
EasyAuto-gradedHeaps, Sorting & Searchdivide-and-conquertwo-pointersmerging

Last updated

Tests divide-and-conquer merging and two-pointer techniques to efficiently combine many pre-sorted lists.

You receive a collection of integer lists, where every individual list is already arranged in non-decreasing order. Your task is to produce one list containing all the integers from every input list, preserving every duplicate and maintaining non-decreasing order throughout.

Write a function that accepts this collection and returns the combined sorted result.

Rules

  • Every integer from every input list must appear in the output exactly as many times as it appears across all inputs combined.
  • Input lists may be empty. The collection itself may also be empty. When there are no integers at all, return an empty list.
  • The order of elements in the output must be non-decreasing.

Constraints

  • 0 ≤ k ≤ 10⁴ where k is the number of lists
  • 0 ≤ length of each list, and the sum of all list lengths is at most 10⁵
  • -10⁹ ≤ each integer ≤ 10⁹
  • Every input list is sorted in non-decreasing order

Examples

Example 1

Input: combine_sorted_lists([[1, 4, 9], [2, 2, 7], [3]])

Output: [1, 2, 2, 3, 4, 7, 9]

Example 2

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

Output: [-5, -5, 0, 10]

Example 3

Input: combine_sorted_lists([])

Output: []

Hints

Hint 1

Consider how you would merge just two sorted lists using two pointers—one for each list.

Hint 2

Instead of merging lists one by one into a growing result, try splitting the collection in half recursively.

Hint 3

The recursion tree will have logarithmic depth in the number of lists, and each level processes all elements exactly once.