The Union‑Find Fellowship: Finding Your Tribe in Code
The Quest Begins (The "Why") I still remember the first time I stared at a LeetCode problem that asked me to count the number of islands in a grid. My initial instinct? Run a BFS/DFS from every unvisited land cell, mark everything reachable, and repeat. It worked, but each query felt like I was re‑exploring the same territory over and over again—like walking the same hallway in a dungeon every time I wanted to open a new door. Then a friend tossed me another problem: “Given a list of friendships, tell me if two people are in the same social circle.” Again, the naive solution was to rebuild the whole graph for every query. I felt like I was stuck in a grind‑fest, repeating the same low‑level work while the real challenge—understanding the structure of the connections—remain. That frustration sparked a question: Is there a way to remember what we’ve already discovered about connectivity, so future queries are instant? The answer, as many of you have guessed, lives in a humble but mighty data structure called Union‑Find (also known as Disjoint Set Union, DSU). The Revelation (The Insight) At its core, Union‑Find is about two simple ideas : Each element starts in its own set – think of every person as a lone adventurer. When we learn that two elements belong together, we merge their sets – we call that a union . The magic isn’t just in merging; it’s in how we find the representative (or “root”) of a set later on. If we naïvely walked up a chain of parents every time, we could end up with O(n) per find—still a grind. Two optimizations turn this into near‑constant time: Union by rank (or size) – always attach the smaller tree under the root of the larger one. This keeps the overall tree shallow, guaranteeing that the height never exceeds log n. Path compression – during a find operation, we make every node we pass point directly to the root. It’s like handing every traveler a map that instantly shows the shortest route to the campfire, so next time they don’t need to trek