Music streaming app~35 min2s · 256 MBtarget O(m log m log n) time, O(n + m log m) spaceunion-find
You work on a music streaming app. Its servers pass audio to each other over relay links. A link can come up and go down during the day. Two servers can reach each other when there is a path of links that are up at that moment.
Your team lead asks: "At each question in the log, can these two servers reach each other?" The whole log of the day is known in advance. It holds up to 10,000 events on up to 10,000 servers.
Write connected_over_time(n, events).
0 to n - 1.events[t] = [kind, a, b] is the event at time t, in order:
1: the link between servers a and b comes up. The link is not up already, and a and b are different.2: the link between a and b goes down. It is up at that moment, and the two numbers can be given in either order.3: question. Can a reach b right now? The answer is 1 or 0. A server reaches itself.At the start, no link is up. A link can come up again after it went down.
Input: n = 5, events = [[1, 0, 1], [1, 1, 2], [3, 0, 2], [2, 1, 2], [3, 0, 2], [1, 3, 4], [1, 2, 3], [3, 2, 4], [3, 0, 4]]
Output: [1, 0, 1, 0]| Time | Event | Links up afterwards | Answer |
|---|---|---|---|
| 0 | up 0-1 | 0-1 | |
| 1 | up 1-2 | 0-1, 1-2 | |
| 2 | can 0 reach 2? | 0-1, 1-2 | 1 |
| 3 | down 1-2 | 0-1 | |
| 4 | can 0 reach 2? | 0-1 | 0 |
| 5 | up 3-4 | 0-1, 3-4 | |
| 6 | up 2-3 | 0-1, 3-4, 2-3 | |
| 7 | can 2 reach 4? | 0-1, 3-4, 2-3 | 1 |
| 8 | can 0 reach 4? | 0-1, 3-4, 2-3 | 0 |
Input: n = 2, events = [[3, 0, 1], [1, 0, 1], [3, 0, 1], [2, 1, 0], [3, 0, 1]]
Output: [0, 1, 0]The link goes down with its ends given in the other order.
Input: n = 1, events = [[3, 0, 0]]
Output: [1]1 ≤ n ≤ 10,0001 ≤ len(events) ≤ 10,000kind is 1, 2 or 3, and every server number is from 0 to n - 1.Building the groups from scratch at every question costs about n plus the number of links that are up, which can be 10,000 or more steps. With 3,000 questions that is about 30 million steps, and the cost grows with the square of the log size. Each link is up for one stretch of time. A segment tree over time can store it on at most 28 nodes, and a union-find that can roll back joins the links as the tree is walked.