KatInterview

Merge Sorted Event Streams with Running Sum

Heaps, Sorting & SearchAuto-graded · 15 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapmergek-way-merge

Last 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 0 before 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^4 where k is the number of streams
  • 0 ≤ N ≤ 10^5 where N is the total number of events across all streams
  • Each event is [time, value] where 0 ≤ time ≤ 10^9 and -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.