The problem, in one line. Given a table saying which cities are directly linked, count the groups of cities that are linked to each other directly or through other cities. LeetCode 547.
The tell. “Directly or indirectly connected” and the answer is a count of groups. Each fact you read either joins two groups or tells you nothing new, and a structure that answers “are these two already in one group?” in a blink is a union-find.
The wrong first idea
Count the links. Start with one group per city and take one away for every pair marked as linked.
return n - sum(is_connected[i][j] for i in range(n) for j in range(i + 1, n))
It works when the links form chains and fails the moment a loop appears. Three cities all linked to each other have three links, so 3 minus 3 gives 0 groups. The answer is 1. The third link joined two cities that were already in the same group, so it should have taken nothing away.
The invariant
Give every city a pointer to a city in its group, and a city pointing at itself is the top of its group. find(x) climbs pointers to the top. Only when two cities have different tops does a link merge anything.
groups = 3
link (0,1): tops 0 and 1 differ, merge, groups = 2
link (0,2): tops 1 and 2 differ, merge, groups = 1
link (1,2): tops 2 and 2 match, nothing to do
The sentence that stays true every step: groups equals the number of cities minus the number of merges that joined two different tops. The climb halves its own path as it goes, so later questions are close to instant.
The solution
def provinces(is_connected):
n = len(is_connected)
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # point at the grandparent as we climb
x = parent[x]
return x
groups = n
for i in range(n):
for j in range(i + 1, n):
if is_connected[i][j]:
a, b = find(i), find(j)
if a != b:
parent[a] = b # two groups become one
groups -= 1
return groups
print(provinces([[1, 1, 0], [1, 1, 0], [0, 0, 1]]))
print(provinces([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))
print(provinces([[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]))
2
4
2
func provinces(m [][]int) int {
n := len(m)
parent := make([]int, n)
for i := range parent {
parent[i] = i
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]] // point at the grandparent as we climb
x = parent[x]
}
return x
}
groups := n
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
if m[i][j] == 1 {
a, b := find(i), find(j)
if a != b {
parent[a] = b // two groups become one
groups--
}
}
}
}
return groups
}
Same three calls print 2, 4, 2.
Complexity
- Time O(n squared), times a tiny inverse-Ackermann factor: the table itself has n times n cells to read, and each merge or climb is close to constant.
- Space O(n): one pointer per city.
Traps
- Subtracting for every link without checking the tops. The triangle
[[1,1,1],[1,1,1],[1,1,1]]then answers 0 instead of 1. - Pointing the city instead of its top:
parent[i] = j. That overwrites the city’s old pointer and cuts it off from the group it already belonged to. - Reading the whole table instead of the upper half. The table is mirrored and the diagonal is all ones, so starting
jati + 1skips both the repeats and the self-links.
Next in the ladder
Redundant Connection keeps the same tops and the same merges, but now the interesting case is the one where the tops already match: that link closes a loop.