Find
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Find asks "who is the leader of this item's group?" by following parent pointers until reaching an item that points to itself. Two items are in the same group exactly when their leaders are the same, which gives a very fast "are they connected?" test.
Practical use cases
- Web app: Are these two users in the same friend circle?. A social app wants to know if Asha and Ravi are linked through any chain of friends. Instead of exploring friend lists layer by layer, it finds the leader of each person and compares them. If the leaders match, they are in the same circle. The answer comes back immediately even when the circle holds hundreds of thousands of members.
- Web app: Are these two offices on the same network?. An IT admin page lets you pick two branch offices and asks if there is any working link path between them. Comparing the group leaders answers instantly, even when thousands of links have been reported. No page waits on a long search, and the same check works for every pair the admin tries.
- System: Compilers and percolation puzzles. Compilers use find to see if two variables are known to be the same thing, and simulations ask whether a path of open cells links top to bottom. Each is a find on two items.
The story: Who Is the Boss of the Boss?
Grandpa Bhaskar's Sunday cricket club had grown big. New players always joined by saying "Zoya brought me" or "I came with Aarav." Nobody ever wrote who the overall captain was. Instead, each player only remembered one person: the one who brought them.
One Sunday, a quarrel broke out. Two players were arguing about whether they were in the same team. Mira had the idea: "Easy! Follow the chain. Ask each person who brought them, then ask that person, and keep going until you meet someone who says: nobody, I started this team."
She tried it on Kabir: Kabir came with Aarav, Aarav came with Zoya, and Zoya said, "I started it." So Zoya was the top of Kabir's team. She tried it on the other player: the chain ended at Zoya too. "Same top boss, same team!" announced Mira.
That chain-walking is called find. It does not need any big register. It only follows the one-pointer-per-person trick until it reaches a root, which is a person who is their own boss.
How to spot this problem, and where you need it
You need to quickly tell whether two things are in the same group, when the groups are formed by many separate "these belong together" facts.
Signs you need it
- The question is "are X and Y connected?" or "do they belong to the same set?".
- You are running a full search through the graph for each question and it gets slow.
- Groups keep changing, so a pre-computed answer table becomes outdated.
- The problem needs a representative or "leader" for each group.
Where to use it in a project
- Friend circle, network and team membership checks in an app.
- Validation steps that must test whether two items were already linked.
The solution
Give each item a parent pointer. To find the leader of an item, keep going to its parent until you reach an item whose parent is itself; that item is the leader. To check whether two items are together, find both leaders and compare them. With the usual speed-ups this takes almost constant time.
Payoff: Before: a fresh search through the whole network per question. After: two quick climbs to the leaders and one comparison.
Explain it like I am 8
Imagine a line of kids each holding the hand of the kid who invited them. To find the leader of the whole group, you keep walking from hand to hand until you reach the kid who is not holding anyone's hand.
How it works, step by step
- Start at your item
x. - Check the boss slot: if
parent[x] == x, you already are the root. Stop and returnx. - Otherwise hop up: set
x = parent[x]and check again. - The root you stop at is the answer. Two items are in the same team exactly when their finds give the same root.
- The cost is the number of hops, which is the height of the tree. Shallow trees give fast finds. The next lessons keep trees short.
The code in four languages
PHP
<?php
// find: walk up until we meet someone who is their own boss
function find(array $parent, int $x): int {
while ($parent[$x] !== $x) {
$x = $parent[$x]; // hop up one level
}
return $x; // the root
}
// the forest from the picture: 4 -> 3 -> 1 -> 0, and 5 -> 3, and 2 -> 1
$parent = [0, 0, 1, 1, 3, 3];
echo "find(4) = " . find($parent, 4) . "\n"; // 0
echo "find(5) = " . find($parent, 5) . "\n"; // 0
echo "find(2) = " . find($parent, 2) . "\n"; // 0
$same = find($parent, 4) === find($parent, 5);
echo "4 and 5 same team? " . ($same ? "yes" : "no") . "\n";JavaScript
// find: walk up until we meet someone who is their own boss
function find(parent, x) {
while (parent[x] !== x) {
x = parent[x]; // hop up one level
}
return x; // the root
}
// the forest from the picture: 4 -> 3 -> 1 -> 0, and 5 -> 3, and 2 -> 1
const parent = [0, 0, 1, 1, 3, 3];
console.log("find(4) = " + find(parent, 4)); // 0
console.log("find(5) = " + find(parent, 5)); // 0
console.log("find(2) = " + find(parent, 2)); // 0
const same = find(parent, 4) === find(parent, 5);
console.log("4 and 5 same team? " + (same ? "yes" : "no"));Java
public class Main {
// find: walk up until we meet someone who is their own boss
static int find(int[] parent, int x) {
while (parent[x] != x) {
x = parent[x]; // hop up one level
}
return x; // the root
}
public static void main(String[] args) {
// the forest from the picture: 4 -> 3 -> 1 -> 0, and 5 -> 3, and 2 -> 1
int[] parent = {0, 0, 1, 1, 3, 3};
System.out.println("find(4) = " + find(parent, 4)); // 0
System.out.println("find(5) = " + find(parent, 5)); // 0
System.out.println("find(2) = " + find(parent, 2)); // 0
boolean same = find(parent, 4) == find(parent, 5);
System.out.println("4 and 5 same team? " + (same ? "yes" : "no"));
}
}Go
package main
import "fmt"
// find: walk up until we meet someone who is their own boss.
func find(parent []int, x int) int {
for parent[x] != x {
x = parent[x] // hop up one level
}
return x // the root
}
func main() {
// the forest from the picture: 4 -> 3 -> 1 -> 0, and 5 -> 3, and 2 -> 1
parent := []int{0, 0, 1, 1, 3, 3}
fmt.Println("find(4) =", find(parent, 4)) // 0
fmt.Println("find(5) =", find(parent, 5)) // 0
fmt.Println("find(2) =", find(parent, 2)) // 0
same := find(parent, 4) == find(parent, 5)
answer := "no"
if same {
answer = "yes"
}
fmt.Println("4 and 5 same team?", answer)
}Time: O(h), up to O(n) · Extra space: O(1). The cost is the number of hops, which is the height of the tree: tiny for short trees, long for a skinny chain.
Watch out for
- Testing
parent[x] == 0instead ofparent[x] == x. Only the second says "I am the root"; item 0 may not even be a root. - Comparing
parent[a] == parent[b]to test for the same team. That only compares direct bosses. Always compare the roots:find(a) == find(b). - Writing the loop with a wrong start so that it never ends when a cycle sneaks in. A valid forest never has a cycle, so keep it that way.
Quick check
- How do you know find has reached the root?
- parent[x] is bigger than x
- The array ends
- The value is 0
- parent[x] equals x
- Players 4 and 5 both have find = 0. What does that mean?
- They are in different teams
- They are in the same team
- They are the roots
- Nothing yet
- What makes a find slow?
- A short tree
- Large numbers
- A tall, skinny tree with many hops
- Too many roots