Sub topic 3
Find: Walking Up to the Root
This chapter assumes you know Python lists and loops, and that you understand a tree as nodes with parent links. The previous chapter showed how a forest of parent pointers represents the sets. This chapter covers the find operation, which answers the question "which set is this element in?"
The idea
Every set in the forest is a tree. Every tree has exactly one root. The root is the only node whose parent is itself. We use the root as the set's name, or representative. To find the set of an element, follow parent pointers upward until you reach a node that points to itself.
Two elements are in the same set exactly when find returns the same root for both.
The array behind this picture is parent = [0, 0, 1, 2, 4, 4]. Index i holds the parent of i. Roots hold their own index.
The code
parent = [0, 0, 1, 2, 4, 4]
def find(x):
while parent[x] != x:
x = parent[x]
return x
print(find(3)) # 0
print(find(5)) # 4
print(find(0)) # 0, a root finds itself immediately
print(find(3) == find(5)) # False, different setsThe loop condition parent[x] != x is the test for "not a root yet". When the loop ends, x is the root.
What find costs
The cost of find(x) is the number of pointer steps from x to its root, which is the depth of x in its tree. A shallow tree gives fast finds. A tall tree gives slow ones.
find never changes the forest, so it is safe to call as often as you like. This is about to change. Later chapters add path compression, which rewrites pointers during the walk. The loop above is the version to compare against.
Seeing the path
To make the walk visible, this variant returns every node it visits:
parent = [0, 0, 1, 2, 4, 4]
def find_path(x):
path = [x]
while parent[x] != x:
x = parent[x]
path.append(x)
return path
print(find_path(3)) # [3, 2, 1, 0]
print(find_path(5)) # [5, 4]The last item is the root. The number of steps is len(path) - 1. This path is exactly what path compression will later flatten.
Common errors
- Comparing elements instead of roots.
parent[a] == parent[b]is wrong for deeper trees. In the example above, elements 3 and 1 have different parents (2 and 0) but share a root. Always comparefind(a) == find(b). - Initializing the array wrongly. The starting state must be
parent = list(range(n)), so every element is its own root. Something like[0] * nmakes every element point at 0, which merges everything into one set. - Creating a cycle. If a non-root pointer ever leads back to itself through other nodes,
findloops forever. Correctunioncode never does this, because it only links one root under another. - Using recursion on tall trees. A recursive
findis shorter to write, but a chain of thousands of nodes can exceed Python's recursion limit. The loop does not have this problem. - Passing an out-of-range index.
find(6)on a six-element array raisesIndexError. Validate input if it comes from outside your code.
Where this leads
find is correct as written, but its speed depends on tree depth. The next chapter, on union, shows how roots get linked. After that, we see how a careless choice of which root goes under which can build a tall chain.
Exercise
Given parent = [1, 2, 2, 2, 3], what does find(4) return, and how many pointer steps does the loop take?
Show answer
find(4) returns 2. The walk is 4 -> 3 -> 2, and parent[2] == 2 so it stops. That is 2 pointer steps, and the path is [4, 3, 2].
Exercise
A learner checks whether elements a and b are in the same set with parent[a] == parent[b]. Give an input where this returns the wrong answer, using parent = [0, 0, 1, 2].
Show answer
Take a = 3 and b = 1. Their parents are 2 and 0, so the check says they differ. But find(3) is 0 and find(1) is 0, so they share a set. The correct check is find(a) == find(b).