Three problems where union-find must answer questions about a past or a threshold. The move: read every question first, then process the events in an order where groups only grow.
You work on a social network, a road planner and a link-monitoring team. The three problems on this street look as if they need more than union-find. They ask when a group first reaches a size, how big the largest group is after each removal, and how strong the best route is.
The Academy lesson Union-find answers "are these connected now?" as links arrive. These problems ask about a moment that is not now. The answer is to change the order of the work.
| Problem | The question | The order of the events |
|---|---|---|
| Earliest moment everyone is connected | the first time a group has k users | logs sorted by time, oldest first |
| Components after removing links in order | the largest group after each removal | removals run backwards, as additions |
| Paths with limits on edge weights | the strongest route for each query | roads sorted by limit, strongest first |
Exercise · Predict the output: Removals run backwards. Links 3 and 0 are removed, in that order. The code joins the links that are never removed, then puts the removed links back in reverse order, recording the largest group before each one. What does it print?
links = [[0, 1], [1, 2], [3, 4], [2, 3]]
removals = [3, 0]
parent = [0, 1, 2, 3, 4]
size = [1, 1, 1, 1, 1]
largest = 1
def find(x):
while parent[x] != x:
x = parent[x]
return x
def join(a, b):
global largest
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
size[rb] += size[ra]
largest = max(largest, size[rb])
for i, (a, b) in enumerate(links):
if i not in removals:
join(a, b)
answer = [0, 0]
for i in range(len(removals) - 1, -1, -1):
answer[i] = largest
join(*links[removals[i]])
print(*answer)Union-find merges and never splits. So ask one question before any code: in what order can I process the events so that groups only grow?
| The question is about | The order that only merges | When to answer |
|---|---|---|
| the first time something happens | sort by time, oldest first | right after a merge, when the size is reached |
| the state after each removal | run backwards: a removal becomes an addition | before putting the link back |
| the best route under a threshold | sort by limit, strongest first | at the merge that puts both ends in one group |
Read every question first. Process the events in an order that only merges, and answer each question at the moment its answer is fixed. A question answered earlier or later reads the wrong groups.
This is called working offline. You may read the whole input before answering, so you choose the order. Online code, which must answer as each event arrives, cannot do this.
The size of each group lives on its root. A merge adds the two sizes, and a running maximum keeps the largest so far. The earliest-moment problem checks the size after every merge, and stops at the first one that reaches k.
Union-find cannot split a group, so run the removals backwards. Record the largest group before each link comes back.
Exercise · Find the bug: Sorted by the wrong column. Each log is [time, a, b]: at that time, users a and b became contacts. This returns the earliest time at which some group has at least k users. Which line is wrong?
def earliest_group_of(users, logs, k):
parent = list(range(users))
size = [1] * users
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for time, a, b in sorted(logs, key=lambda log: log[1]):
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
size[rb] += size[ra]
if size[rb] >= k:
return time
return -1The Academy lesson Union-find answers questions as links arrive. Sort, then choose shows why a sorted order is safe. This street changes three things.
Time runs backwards. For 50,000 links, all removed one by one, rebuilding the groups after each removal costs 1,250,025,000 joins. Running the removals backwards costs 50,000.
Waiting lists merge small into large. Each group keeps the queries with an end in it, and a merge scans only the shorter list. Take 4,096 groups merging one after another into a growing group. Scanning the shorter list costs 4,095 steps, and scanning the longer list costs 8,386,560.
The record comes before the merge. On the example network of 6 users and 6 links, with the removals 1, 5, 3 and 0, the right answers are 6, 4, 2 and 2. Putting each link back before recording gives 6, 6, 4 and 2, which is the state before the removal, not after it.
In all three cases nothing is recomputed. Each event is processed once, in the order you chose, and each question is read from state that already exists. The whole method costs about one sort and one pass of union-find.
Record the largest group before putting a link back. Recording after gives the state before the removal, not after it.
Exercise · Break it: Record after putting the link back. This returns the largest group after each removal. It runs the removals backwards, but puts each link back before recording the answer. Find an input where it gives the wrong answer.
def largest_after_removals(users, links, removals):
parent = list(range(users))
size = [1] * users
largest = 1
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def join(a, b):
nonlocal largest
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
size[rb] += size[ra]
largest = max(largest, size[rb])
gone = set(removals)
for i, (a, b) in enumerate(links):
if i not in gone:
join(a, b)
answer = [0] * len(removals)
for i in range(len(removals) - 1, -1, -1):
join(*links[removals[i]])
answer[i] = largest
return answerSolve them in this order. The first sorts by time, the second runs time backwards, and the third sorts by limit and keeps waiting lists.
Before you code each problem, write two lines: the order in which the events only merge, and the moment at which each question is answered. If the first line is not clear, check whether time should run backwards.
Give each problem about 25 minutes. Spend the first four on the two lines, and say them aloud as you would to an interviewer. Then write what the answer is for a question that never gets answered. Read the whole input once before you write any loop.
Three edge cases return on every rung. Several events may share a time, so read them all before you answer. A link may join users who are already together, and it changes nothing. A question may name the same item twice.
When a solution fails, check the order before the loop. Most wrong answers on this street come from sorting by the wrong field, or from recording an answer on the wrong side of a merge.
Checkpoint · Offline queries
Q1/5 Why can union-find not answer "the largest group after each removal" by processing the removals in order?
Answer: B
A removal splits a group, and union-find has no way to do that. Run the removals backwards, so each one becomes a merge.
Q2/5 Removals run backwards. When do you record the largest group for a removal?
Answer: B
The answer describes the network right after that link is gone, and in reverse order the link is still absent before you put it back.
Q3/5 Roads are read from the highest limit down. When is a query for two towns answered?
Answer: C
The limit of that road is the weakest road on the best route, so it is the answer. Earlier merges do not yet connect both ends.
Q4/5 Two groups merge, and each keeps a list of waiting queries. Which list do you scan?
Answer: C
Each query then moves only into a list at least twice as long, so it moves at most log q times. Scanning the longer list can cost 8,386,560 steps for 4,096 groups.
Q5/5 Logs are [time, a, b]. You sort them to find the earliest time a group reaches size k. Which field do you sort by?
Answer: C
The question is about time, so the events must be read in order of time. Sorting by a user number reads them in a meaningless order.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.