Eight problems that group things by a shared key or an equality. The move: turn every link into a union of two roots, keep each group's property at its root, and read the answer from the roots.
You work on a login system, a part catalogue and a map of banners. In each, items are linked by something they share, and you need the groups the links make.
The Academy lesson Union-find builds the structure: find a root, union two roots, and count the groups. On this street the structure is the same, and the work is to turn each story into unions. The table shows the elements and the link for each problem.
| Problem | The elements | What links two of them | The answer from the roots |
|---|---|---|---|
| Satisfiable equalities | names | a rule that says equal | no inequality joins one group |
| Smallest equivalent string | letters | a pair of synonyms | the smallest letter of each group |
| Provinces by a limit | towns | an entry below the limit | the number of groups |
| Shared logins | devices and logins | a device uses a login | the number of groups of one size |
| Stones | rows and columns | a stone in both | stones minus groups |
| Spare cables | hubs | a cable | groups minus 1, if cables suffice |
| Merged accounts | profiles | a shared card | the merged profile of each group |
| Common factors | numbers and primes | a shared prime | the size of the biggest group |
Read the second and third columns first. They tell you which unions to write, and the code is the same each time.
Exercise · Predict the output: Stones in rows and columns. Stones sit at (0,0), (0,2), (1,1), (2,0) and (2,2). Two stones are linked when they share a row or a column. The code joins each stone's row and column, and prints the number of stones minus the number of groups. What does it print?
parent = list(range(200))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
stones = [[0, 0], [0, 2], [1, 1], [2, 0], [2, 2]]
for r, c in stones:
parent[find(r)] = find(100 + c)
groups = {find(r) for r, c in stones}
print(len(stones) - len(groups))Two items are in the same group exactly when they have the same root. A link is a union of the two roots, and never of the two items alone, so every member of both groups moves together.
Two items are in one group exactly when find gives the same root. A link joins the two roots. Whatever the group needs, such as its size or smallest letter, is kept at the root and updated on a join.
Name the elements first. Sometimes they are the items. Sometimes the link needs a second kind of element: a login that joins devices, a prime that joins numbers, or a row and a column that join stones. When the link is a shared key, either union each item with the first item that had the key, or make the key an element of its own.
Then ask what the answer reads from the roots. It may be the number of groups, the biggest size, or a value such as the smallest letter. Keep that value at the root when you union.
On the stones, the elements are rows and columns, and a stone is a union of its row and its column. Of 5 stones in 2 groups, you can remove 3, because each group must keep one stone.
A stone joins its row and its column. Each group keeps one stone, so removable stones are stones minus groups.
Exercise · Find the bug: Not enough cables. A data hall has n hubs and some cables. A move takes a spare cable and puts it between two groups. The function returns the fewest moves to connect every hub, or -1 when there are too few cables. Which line is wrong?
def moves_to_connect(n, cables):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
groups = n
for a, b in cables:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
groups -= 1
return groups - 1 if len(cables) >= n else -1Union-find builds find and union, and Cycles, colouring and components shows components by a walk. This street changes four things.
The link goes through a key. Take numbers 4, 6, 15 and 35. The primes 2, 3 and 5 join 4 to 6, 6 to 15 and 15 to 35, so all 4 numbers form one group. No pair was compared, because each number is factored once and joined to the first number with each prime.
The answer is read from the roots. Six stones in rows and columns [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] form 1 group, so 5 can be removed. With 6 hubs and cables 0-1, 0-2, 0-3, 1-2 and 1-3, there are 3 groups and 5 cables, so 2 moves connect them. Four hubs with only 2 cables cannot be connected, and the answer is -1.
A property lives at the root. For synonyms of parker and morris, joining two groups keeps the smaller letter as the root. The base word parser becomes makkek. Hello and world with the base hold become hdld.
Order matters. For the rules a == b, b != c and c == a, checking b != c straight away passes. After the third rule, b and c are in one group, so the rules cannot all hold. Apply every equality first, then check the inequalities.
Apply every equality before any inequality. A later equality can join two letters that an earlier check saw apart.
Exercise · Put it in order: Equalities first. Arrange the lines into a function that says whether a list of rules about letters can all hold. A rule looks like "a==b" or "a!=b". A helper that finds the root of a letter is given above.
def consistent(rules):
parent = list(range(26))
for r in rules:
if r[1] == "=":
parent[find(parent, ord(r[0]) - 97)] = find(parent, ord(r[3]) - 97)
for r in rules:
if r[1] == "!" and find(parent, ord(r[0]) - 97) == find(parent, ord(r[3]) - 97):
return False
return True
parent = [0] * 26Solve them in this order. The first three join the items themselves. The next three add a second kind of element or count the groups. The last two merge values or join through a key.
Before each problem, write three lines: what the elements are, what links two of them, and what the answer reads from the roots. Then write the unions, and the read-out last.
Give each problem about 25 minutes. Spend the first five on the three lines. Run the unions by hand on four items, and check that each find gives the root you expect.
Three edge cases return on every rung. An item with no link is a group of one, and it must still count. A link between two items already in one group must change nothing. And an item that never appears in the input, such as an empty account, must not be forgotten when you count groups.
When a solution fails, print the root of every item after all unions. A wrong answer here usually means two items were joined instead of their roots, or a check ran before the last union.
Checkpoint · Union-find patterns
Q1/5 When are two items in the same group?
Answer: B
Links may be indirect, through a chain. The root identifies the group, so equal roots mean one group.
Q2/5 Numbers 4, 6, 15 and 35 are joined when they share a prime factor. How many groups are there?
Answer: D
4 and 6 share 2, 6 and 15 share 3, and 15 and 35 share 5. All four numbers end up in one group.
Q3/5 Five stones form 2 groups by shared rows and columns. How many stones can be removed if each group keeps one?
Answer: B
Each group keeps one stone, so 5 - 2 = 3 stones can be removed.
Q4/5 The rules are a == b, b != c, c == a. Why must you apply all the equalities first?
Answer: B
Checking b != c at once passes. After c == a, b and c share a group, so the rules contradict each other.
Q5/5 A network has 3 hubs and 2 cables forming a chain. What is the fewest moves to connect it?
Answer: B
Three hubs need at least 2 cables, and the chain already has them, so the answer is 0.
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.