Social feed~35 min2s · 256 MBtarget O((n + m) α(n)) time, O(n + m) spaceclassic twin: lc-803union-find
A social app has users numbered from 0. Two users are linked when they follow each other. A community is a set of users who can reach one another through a chain of links.
A moderation tool removes links one by one, for example when accounts are blocked. After each removal the team wants the size of the largest community that is left.
Write largest_group_after_removals(users, links, removals).
users is the number of users, numbered 0 to users - 1.links[i] is [a, b], a link between users a and b. A link may join a user to itself, and two links may join the same pair.removals lists link numbers, all different. The link links[removals[0]] is removed first, then links[removals[1]], and so on. Links not listed stay.Input: users = 6, links = [[0,1],[1,2],[2,3],[3,4],[4,5],[1,4]], removals = [1,5,3,0]
Output: [6, 4, 2, 2]A structure that joins groups cannot split them. So the solution runs time backwards. It starts after the last removal, then puts the links back one by one.
| Step | Link put back | Answer recorded | Largest group after it |
|---|---|---|---|
| start | 2, from the links [2,3] and [4,5] that are never removed |
||
| 1 | links[0] = [0,1] |
removal 3: 2 | 2 |
| 2 | links[3] = [3,4] |
removal 2: 2 | 4 |
| 3 | links[5] = [1,4] |
removal 1: 4 | 6 |
| 4 | links[1] = [1,2] |
removal 0: 6 | 6 |
Read from the first removal, the answers are 6, 4, 2 and 2.
Input: users = 4, links = [[0,1],[1,2]], removals = []
Output: []Nothing is removed, so there is nothing to report.
Input: users = 2, links = [[0,1]], removals = [0]
Output: [1]After the only link goes, both users are alone.
1 ≤ users ≤ 100,0000 ≤ len(links) ≤ 100,000, and every user number is from 0 to users - 10 ≤ len(removals) ≤ len(links), with different link numbersRecomputing the communities after each removal costs about 100,000 links per removal, which is 10,000,000,000 steps in all. A structure that can only join must be used, so the removals have to be turned into additions.