KatInterview

Combine Several Ascending Sequences into One Sorted Sequence

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapk-way-mergedivide-and-conquer

Last updated

Merge k individually sorted integer arrays into a single sorted array, testing heap-based k-way merging or pairwise divide-and-conquer and the associated complexity analysis.

You are given a collection of k integer arrays. Every array is already sorted in non-decreasing (ascending) order. Some arrays may be empty.

Produce one array that contains every element from every input array, arranged in non-decreasing order.

Task

Implement combine_sorted_arrays(arrays), which receives a list of sorted lists of integers and returns a single sorted list holding all of their elements.

Rules

  • Every element of every input array must appear in the output exactly as many times as it appears in the inputs. Duplicates, including duplicates that occur across different arrays, are all kept.
  • The output must be in non-decreasing order.
  • If the outer list is empty, or every inner list is empty, return an empty list.
  • If there is only one inner list, its contents are the answer.
  • Values may be negative, and the inner lists may have very different lengths.

Let N be the total number of elements across all arrays. A solution that simply concatenates everything and sorts is correct but ignores the fact that the inputs are already sorted. Aim for roughly O(N log k) time.

Constraints

  • 0 <= k <= 10^4
  • Each inner list has length between 0 and 500
  • 0 <= N <= 10^4 in total (typical test sizes)
  • Each value is an integer in the range [-10^4, 10^4]
  • Each inner list is sorted in non-decreasing order

Examples

Example 1

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

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

Example 2

Input: combine_sorted_arrays([[], [], []])

Output: []

Example 3

Input: combine_sorted_arrays([[1], [0]])

Output: [0, 1]

Hints

Hint 1

At every step, the next value to output must be the smallest among the first not-yet-used element of each array. How can you find that minimum quickly when k is large?

Hint 2

A min-heap holding at most one entry per array (the value plus which array and which position it came from) lets you pop the smallest in O(log k) and then push the next element from the same array.

Hint 3

Alternative: merge the arrays in pairs, round after round, like the merge step of merge sort. That takes about log2(k) rounds, each costing O(N), for O(N log k) overall. Merging them one after another into a growing result is slower, around O(kN).