KatInterview

Merge Multiple Sorted Series with Grouping

Heaps, Sorting & SearchAuto-graded · 16 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaps-sortingarraystwo-pointers

Last updated

Efficiently merge K pre-sorted event logs while combining entries sharing identical timestamps.

You are given a list of $K$ event streams. Each individual stream is a list of dictionaries, where each dictionary contains two keys: "timestamp" (an integer) and "value" (a string).

Every stream is strictly ordered in ascending order by "timestamp". Within any single stream, timestamps are unique.

Write a function merge_streams that merges all $K$ streams into a single ordered list of dictionaries. The merged result must satisfy the following conditions:

  • The output list must be sorted by "timestamp" in strictly ascending order.
  • If the same "timestamp" appears in multiple streams, combine all associated values into a single list of strings under the "value" key for that timestamp.
  • Values associated with identical timestamps must appear in order of their stream index (i.e., values from earlier streams in the input list come before values from later streams).

Constraints

  • $0 \le K \le 1000$ (where $K$ is the number of streams).
  • $0 \le N \le 10^5$ total elements across all streams combined.
  • Timestamps are integers.
  • Within a single stream, timestamps are strictly increasing.

Edge Cases

  • An empty input list of streams ([]) returns an empty list [].
  • Inner streams can be empty.
  • If a timestamp occurs in only one stream, its "value" key in the output should still contain a list with a single element.

Examples

Example 1

Input: merge_streams([[{'timestamp': 1, 'value': 'A'}, {'timestamp': 3, 'value': 'B'}], [{'timestamp': 1, 'value': 'C'}, {'timestamp': 2, 'value': 'D'}]])

Output: [{'timestamp': 1, 'value': ['A', 'C']}, {'timestamp': 2, 'value': ['D']}, {'timestamp': 3, 'value': ['B']}]

Hints

Hint 1

Since each individual stream is already sorted, consider using a min-heap to keep track of the smallest unmerged element across all streams.

Hint 2

To prevent Python comparison errors on dictionary elements when timestamps tie, store explicit tuple indices (timestamp, stream_index, element_index) inside the heap.

Hint 3

Grouping items with the same timestamp can be done consecutively as elements are popped off the min-heap.