Merge Sorted Event Streams with Running Sum
Heaps, Sorting & SearchAuto-graded · 15 test casesLast updated
Tests k-way merging of pre-sorted sequences using a min-heap, deterministic tie-breaking by source index, and accumulating a running total across all events.
You are given k separate event streams, where each stream is a list of events. Every event is a pair [time, value] representing a value change that occurred at a particular time. Within each stream, events are already sorted by time in non-decreasing order, but the streams themselves are independent and unordered relative to each other.
Your task is to merge all events from all streams into a single chronological sequence and compute a running sum that starts at 0 and is updated by each event's value as it is processed. Return a list containing the running sum immediately after processing each event, in the order the events are processed.
Processing order:
- Events are processed in ascending order of their time values.
- When two events from different streams have the same time, the event from the stream with the smaller index (earlier position in the input list) is processed first.
- When multiple events within the same stream share the same time, they are processed in the order they appear in that stream (which is already their given order).
In other words, the effective sort key for any event is (time, stream_index, position_within_stream), all compared in ascending order.
Running sum:
- Starts at
0before any event is processed. - Each event adjusts the sum by adding its
value(which may be negative). - After processing each event, record the updated sum in the output.
Edge cases:
- A stream may be empty; it contributes no events.
- If all streams are empty, return an empty list.
- Values can be negative, and the running sum can go below zero.
Constraints
0 ≤ k ≤ 10^4wherekis the number of streams0 ≤ N ≤ 10^5whereNis the total number of events across all streams- Each event is
[time, value]where0 ≤ time ≤ 10^9and-10^6 ≤ value ≤ 10^6 - Within each stream, times are non-decreasing
- The running sum stays within
[-10^11, 10^11]
Examples
Example 1
Input: merge_event_streams([[[1, 10], [1, -3], [5, 2]], [[1, 4], [3, -1]]])
Output: [10, 7, 11, 10, 12]
Hints
Hint 1
Consider using a min-heap to efficiently track the next event to process from each stream.
Hint 2
The heap should store entries with keys that reflect the tie-breaking rules: (time, stream_index, position).
Hint 3
Initialize the heap with the first event from each non-empty stream, then repeatedly pop the minimum and push the next event from that same stream.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires merging multiple pre-sorted sequences into a single sorted sequence while maintaining a running sum. This is a classic k-way merge problem, optimally solved using a min-heap.
Strategy:
-
Heap initialization: Create a min-heap and insert the first event from each non-empty stream. Each heap entry contains
(time, stream_index, position, value)so that Python's default tuple comparison automatically implements our tie-breaking rules. -
Iterative processing: Repeatedly extract the minimum event from the heap (this is guaranteed to be the next event in chronological order), add its value to the running sum, and record the new sum. Then, if that stream has more events, insert its next event into the heap.
-
Termination: When the heap becomes empty, all events have been processed.
Why this works:
At any moment, the heap contains at most one candidate event from each stream—specifically, the earliest unprocessed event from that stream. Since each stream is already sorted, the overall next event must be the minimum among these candidates. No event can appear earlier than the candidates in the heap, because any earlier event from a given stream would either already be processed or be the current candidate for that stream.
Correctness of tie-breaking:
When two events have the same time, the tuple comparison in the heap naturally breaks ties by stream_index (lower index wins), and if both time and stream_index match (same stream), it breaks by position (earlier position wins). This exactly matches the required processing order.
Edge cases:
- Empty streams are skipped during initialization.
- If all streams are empty, the heap starts empty and the result is an empty list.
- Negative values work naturally since we're just accumulating a sum.
Complexity
- Time: O(N log k) where N is the total number of events and k is the number of streams. Each event is pushed and popped from the heap exactly once, and each heap operation takes O(log k) time since the heap never holds more than k elements.
- Space: O(k) for the heap, plus O(N) for the output list.
Solution
import heapq
from typing import List
def merge_event_streams(streams: List[List[List[int]]]) -> List[int]:
heap = []
# Initialize heap with the first event from each non-empty stream
for stream_idx, events in enumerate(streams):
if events:
time, value = events[0]
heapq.heappush(heap, (time, stream_idx, 0, value))
running_sum = 0
result = []
# Process events in order by repeatedly taking the minimum
while heap:
time, stream_idx, pos, value = heapq.heappop(heap)
running_sum += value
result.append(running_sum)
# Add the next event from the same stream if it exists
next_pos = pos + 1
if next_pos < len(streams[stream_idx]):
next_time, next_value = streams[stream_idx][next_pos]
heapq.heappush(heap, (next_time, stream_idx, next_pos, next_value))
return result