Merge Multiple Sorted Series with Grouping
Heaps, Sorting & SearchAuto-graded · 16 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem can be efficiently solved using a $K$-way merge strategy with a min-heap (priority queue).
Since each individual stream is already sorted by timestamp:
- We initialize a min-heap storing tuples of
(timestamp, stream_index, element_index). We populate the heap with the first element of each non-empty stream. Includingstream_indexprevents comparison errors when two timestamps are identical and maintains the required order of values across streams. - At each step, we check the minimum timestamp currently at the top of the heap.
- We repeatedly pop all items matching this minimum timestamp, collecting their
"value"strings into a list in stream order. - Whenever an item is popped from
stream_index, we advance to the next element in that same stream (element_index + 1) and push it onto the heap if it exists. - We output a dictionary
{"timestamp": current_timestamp, "value": combined_values}and repeat until the heap is empty.
Complexity
- Time Complexity: $\mathcal{O}(N \log K)$, where $N$ is the total number of items across all streams and $K$ is the number of streams. Each of the $N$ items is pushed into and popped from the min-heap at most once. Heap operations take $\mathcal{O}(\log K)$ time.
- Space Complexity: $\mathcal{O}(K)$ auxiliary space for the heap (excluding the output list), as the heap never holds more than $K$ elements at any given time.
Python 3 Reference Solution
import heapq
from typing import Dict, List
def merge_streams(streams: List[List[Dict]]) -> List[Dict]:
heap = []
# Seed the min-heap with the first element from each non-empty stream
for stream_index, stream in enumerate(streams):
if stream:
heapq.heappush(heap, (stream[0]['timestamp'], stream_index, 0))
result = []
while heap:
timestamp = heap[0][0]
values = []
# Pop all stream heads sharing the current minimum timestamp
while heap and heap[0][0] == timestamp:
_, stream_index, item_index = heapq.heappop(heap)
item = streams[stream_index][item_index]
values.append(item['value'])
# Push the next element from the same stream if available
next_index = item_index + 1
if next_index < len(streams[stream_index]):
next_item = streams[stream_index][next_index]
heapq.heappush(heap, (next_item['timestamp'], stream_index, next_index))
result.append({'timestamp': timestamp, 'value': values})
return result