Social feed~30 min2s · 256 MBtarget O(m log n) time, O(n + m) spaceunion-find
You work on a social app where moderators merge interest groups. Each of the n people starts in a group of one. A moderator can link two people, which merges their groups, and can undo the most recent link if it was a mistake. Other staff ask whether two people are in the same group, or how big a person's group is.
Your team lead asks: "Answer every question as the actions come in." A log holds up to 100,000 actions.
Write answers_with_undo(n, ops).
0 to n - 1.ops[i] = [kind, a, b] is one action. There are four kinds:
1: link people a and b. Their groups merge.2: undo the most recent link that has not been undone yet. Then a and b are 0 and are ignored. With nothing to undo, it does nothing.3: question. Are a and b in the same group? The answer is 1 or 0.4: question. How many people are in the group of a? Then b is 0 and is ignored.Every link counts as one step for undo, even when a and b were already in one group. Undoing such a link changes nothing.
Input: n = 5, ops = [[1, 0, 1], [1, 1, 2], [3, 0, 2], [4, 1, 0], [2, 0, 0], [3, 0, 2], [4, 1, 0], [1, 3, 4], [4, 4, 0], [2, 0, 0], [2, 0, 0], [4, 1, 0]]
Output: [1, 3, 0, 2, 2, 1]| Action | Groups after it | Answer |
|---|---|---|
| link 0 1 | {0, 1}, {2}, {3}, {4} | |
| link 1 2 | {0, 1, 2}, {3}, {4} | |
| same 0 2 | 1 | |
| size of 1 | 3 | |
| undo | {0, 1}, {2}, {3}, {4} | |
| same 0 2 | 0 | |
| size of 1 | 2 | |
| link 3 4 | {0, 1}, {2}, {3, 4} | |
| size of 4 | 2 | |
| undo | {0, 1}, {2}, {3}, {4} | |
| undo | all alone | |
| size of 1 | 1 |
Input: n = 3, ops = [[2, 0, 0], [1, 0, 1], [1, 0, 1], [2, 0, 0], [3, 0, 1], [2, 0, 0], [3, 0, 1]]
Output: [1, 0]The first undo has nothing to undo. The second link joins nobody, so undoing it changes nothing and 0 and 1 stay together. The next undo removes the first link.
Input: n = 1, ops = [[4, 0, 0]]
Output: [1]1 ≤ n ≤ 100,0001 ≤ len(ops) ≤ 100,000kind is 1, 2, 3 or 4, and every person number is from 0 to n - 1.Answering each question by searching the whole network from scratch costs about n plus the number of links, up to 200,000 steps. For 100,000 questions that is 20 billion steps. Union-find answers a question in a few steps, but a standard version cannot take a merge back. A version that changes one array entry per merge can undo it.