You are given several streams of chat messages from different sources. Each stream is a list of messages sorted by timestamp in ascending order, and each message is a pair [timestamp, message_id].
Merge all streams into a single list sorted by timestamp. When two messages have the same timestamp, order them by message_id ascending.
Remove duplicate messages. Messages with the same message_id are duplicates, even when their timestamps differ. Keep only the first occurrence in the merged chronological order and drop the others.
Function Signature
def merge_streams(streams: list[list[list[int]]]) -> list[list[int]]:
Rules
-
Each stream is a list of
[timestamp, message_id]
pairs. A stream may be empty.
-
Inside one stream, messages are sorted by timestamp ascending, and messages with equal timestamps are sorted by
message_id
ascending.
-
The output is sorted by
(timestamp, message_id)
ascending. For a
message_id
that appears more than once, the kept copy is the one that comes first in that order, which is the copy with the smallest timestamp.
-
Return each kept message as a two-element list
[timestamp, message_id]
. If every stream is empty, return
[]
.
Constraints
-
1 <= len(streams) <= 100
-
0 <= len(streams[i]) <= 1000
-
0 <= timestamp <= 10^9
-
0 <= message_id <= 10^9
-
Each individual stream is sorted by timestamp in ascending order.
Examples
Input: streams = [[[1,101],[3,103],[5,105]], [[2,102],[4,104],[6,106]], [[1,107],[3,103],[7,108]]]
Output: [[1,101],[1,107],[2,102],[3,103],[4,104],[5,105],[6,106],[7,108]]
The three streams interleave by timestamp, and at timestamp 1 message 101 comes before 107. Message 103 appears in the first and third streams, so only one copy is kept.
Input: streams = [[[1,1],[2,2]], [[1,1],[2,2]]]
Output: [[1,1],[2,2]]
Both streams hold the same two messages, so each message_id is kept once.
Input: streams = [[[2,7],[5,9]], [], [[3,4],[3,9],[8,7]]]
Output: [[2,7],[3,4],[3,9]]
The empty stream contributes nothing. Message 9 first appears at timestamp 3, so the copy at timestamp 5 is dropped, and message 7 first appears at timestamp 2, so the copy at timestamp 8 is dropped.