Engineering platform~25 min2s · 256 MBtarget O((n + m) α(n)) time, O(n + m) spaceunion-find
You work on the engineering platform behind an app. Its n data centres are joined by network links. When a link fails, the data centres on its two sides may stop reaching each other. A group is a set of data centres that can all reach one another, directly or through other centres.
During an incident, links fail one at a time and none comes back. Your team lead asks: "After each failure, how many separate groups does the network have?" The network can have 50,000 data centres and 100,000 links, and every link can fail.
Write pieces_after_each_cut(n, links, cuts).
n is the number of data centres, numbered 0 to n - 1.links[i] = [a, b] is the i-th link. Several links can join the same two centres.cuts lists the failures in order. cuts[j] is the index of a link that fails at step j. Every index appears at most once, and no link comes back.cuts[j] and all earlier failed links are gone.If there are no failures, return an empty list.
Input: n = 6, links = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5]], cuts = [4, 0, 2, 1]
Output: [3, 3, 4, 5]The links 0 to 3 form a ring through the centres 0, 1, 2 and 3. The link 4 joins 4 and 5. At the start there are 2 groups.
| Failure | Link | Links left | Groups |
|---|---|---|---|
| 0 | 4: 4 to 5 | 0, 1, 2, 3 | 3: {0, 1, 2, 3}, {4}, {5} |
| 1 | 0: 0 to 1 | 1, 2, 3 | 3: the ring is still a path |
| 2 | 2: 2 to 3 | 1, 3 | 4: {1, 2}, {0, 3}, {4}, {5} |
| 3 | 1: 1 to 2 | 3 | 5: {0, 3}, {1}, {2}, {4}, {5} |
Input: n = 1, links = [], cuts = []
Output: []Input: n = 4, links = [[0, 1], [1, 2], [2, 3]], cuts = [1, 0, 2]
Output: [2, 3, 4]1 ≤ n ≤ 50,0000 ≤ len(links) ≤ 100,000, and each link joins two numbers from 0 to n - 1.0 ≤ len(cuts) ≤ len(links), and the indexes in cuts are different from each other.Building the groups again after every failure costs the whole network each time. For 100,000 failures that is at least 15 billion steps. A union-find structure merges groups quickly but cannot split them. Failures run backwards are additions, and additions are exactly what union-find does.