Chat app~20 min2s · 256 MBtarget O(n + m) time, O(n + m) spacemerge-sorted · hashing
A messaging app sends notifications to a phone from two sources: the app server and a push gateway. Each source keeps its own list, in time order. Some notifications travel through both sources.
The phone must show one list in time order, and it must show each notification once. When both sources hold something at the same second, the app server comes first.
Write merge_streams(times_a, ids_a, times_b, ids_b).
ids_a[i] at second times_a[i]. Stream B has the same shape in times_b and ids_b. Each list of times never goes down.Input: times_a = [1, 4, 4, 9], ids_a = [11, 12, 13, 14], times_b = [2, 4, 5, 9], ids_b = [21, 12, 22, 14]
Output: [11, 21, 12, 13, 22, 14]The trace takes the earlier notification each time, and A wins a tie.
| Step | Taken from | Notification | Result |
|---|---|---|---|
| 0 | A, time 1 | 11 | sent |
| 1 | B, time 2 | 21 | sent |
| 2 | A, time 4 | 12 | sent |
| 3 | A, time 4 | 13 | sent |
| 4 | B, time 4 | 12 | skipped: already sent |
| 5 | B, time 5 | 22 | sent |
| 6 | A, time 9 | 14 | sent |
| 7 | B, time 9 | 14 | skipped: already sent |
Notification 12 is in both streams at time 4, so the copy from B is skipped. Notification 14 is in both streams at time 9, so the copy from B is skipped again. Six ids are shown.
Input: times_a = [5, 5, 5], ids_a = [1, 2, 1], times_b = [5], ids_b = [3]
Output: [1, 2, 3]All four notifications arrive at second 5, so stream A comes first, in its own order. The second copy of id 1 is skipped, and id 3 from stream B follows.
Input: times_a = [1, 2], ids_a = [1, 2], times_b = [10, 20], ids_b = [3, 4]
Output: [1, 2, 3, 4]Stream A is used up before stream B starts. The rest of B follows, and the output is 1, 2, 3, 4.
1 ≤ times_a.length, times_b.length ≤ 100,000; each id list has the length of its time list0 ≤ times ≤ 2,678,400 (seconds since the start of the month), never going down in each list1 ≤ ids ≤ 1,000,000,000Sorting the joined lists costs O((n + m) log (n + m)), which is fine, but both lists are already sorted. A merge with two pointers needs only n + m steps. A set of the ids already shown answers "seen before?" in one step. Checking the output list for each id would cost about 10^10 steps.