KatInterview

Combine K Sorted Sequences into One

Heaps, Sorting & SearchAuto-graded · 21 test cases

Last updated

Tests whether a candidate can use a min-heap to efficiently merge multiple sorted lists into a single sorted output in O(N log k) time.

Problem

You have k sequences of integers, each one already sorted in non-decreasing order. Your job is to combine all of them into one sorted sequence containing every element across all inputs.

A brute-force approach — scanning the front of every sequence at each step to find the next smallest value — becomes unacceptably slow as k grows large. Your solution must do better.

Task

Given a list of k sorted integer lists, return a single list with all elements in non-decreasing order.

Constraints

  • 1 <= k <= 10^5
  • Each individual list may be empty or contain any number of elements.
  • The total number of elements N across all lists satisfies 0 <= N <= 10^6.
  • All integer values fit in a 32-bit signed range.
  • Your solution must run in O(k + N log k) time. An O(N·k) solution is not acceptable.

Examples

Example 1

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

Output: [0, 1, 2, 3, 4, 6, 7, 8, 9]

Hints

Hint 1

At any moment, the next element of the merged output must be the minimum among the current front elements of all lists. What data structure retrieves and replaces a minimum in O(log k) rather than O(k)?

Hint 2

Store a tuple of (value, list_index, position_within_list) in the heap. The list_index and position let you locate and enqueue the successor element after a pop — without those two pieces, you have no way to know where to look next.

Hint 3

Seed the heap once using heapify, which costs O(k). Then every element is pushed and popped exactly once, each costing O(log k), giving O(k + N log k) overall. Watch out for empty input lists: attempting to read index 0 of an empty list will crash.