KatInterview

Merge Sorted Streams with Memory Constraint

Heaps, Sorting & SearchAuto-graded · 22 test cases

Last updated

Tests heap-based merging of multiple sorted sequences under strict O(k) space while maintaining stable duplicate handling.

You are given k sorted lists of integers and a limit count. Your task is to merge these lists into a single sorted sequence and return the first count elements from that sequence.

Each input list is already sorted in ascending order. When multiple lists contain the same value, you must preserve all duplicates and maintain stability: if list i and list j both contain value v, and i < j, then all copies of v from list i must appear before any copy of v from list j in the output.

Your solution must use O(k) auxiliary space, where k is the number of input lists. You may assume all integers fit in memory, but you cannot load entire lists at once beyond what is needed for the merging process.

Write a function that takes a list of sorted integer lists and a count, then returns a list containing up to count elements in globally sorted order with stable duplicates.

Constraints

  • 0 ≤ k ≤ 10⁴ (number of input lists)
  • 0 ≤ count ≤ 10⁶
  • 0 ≤ length of each list ≤ 10⁶
  • -10⁹ ≤ integer values ≤ 10⁹
  • Each input list is sorted in non-decreasing order
  • Auxiliary space must be O(k), not counting the output array

Examples

Example 1

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

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

Example 2

Input: merge_sorted_lists([[1, 1, 3], [1, 2, 2], []], 8)

Output: [1, 1, 1, 2, 2, 3]

Example 3

Input: merge_sorted_lists([[5, 6, 7]], 2)

Output: [5, 6]

Example 4

Input: merge_sorted_lists([[], [], []], 10)

Output: []

Hints

Hint 1

The smallest unprocessed element overall must be at the front of one of the remaining lists.

Hint 2

Use a min-heap to track the current front element of each active list, along with which list it came from.

Hint 3

When values are equal, the list index can serve as a tie-breaker to ensure stable output.