Interview's MateDSA Visualizer
Interview's Mate

DSA Visualizer

Learn by watching algorithms run

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
All topics
PROBLEM-SOLVING TECHNIQUES

Union Find

Track which items share a group, with near-constant-time merges.

Advanced6 problems2 interactive subtopicsO(E · α(n)) time · O(n) space
Practice in AI DSA
WalkthroughOverviewRecognize itMistakes & edge casesKnowledge check (3)Practice
Algorithms & custom examples (2)Open in full playground →
STEP 1/4Everyone starts alone
every node is its own root
parent
123
1
2
3
1
2
3
rootrootroot
  • current
  • active this step
Space Play←→ StepR Replay
1 / 4
PYTHONedges = [[1, 2], [1, 3], [2, 3]]
1def find_redundant_connection(edges):
▶2 parent = list(range(len(edges) + 1))
3 def find(x):
4 while parent[x] != x:
5 parent[x] = parent[parent[x]]
6 x = parent[x]
7 return x
8 for a, b in edges:
9 ra, rb = find(a), find(b)
10 if ra == rb:
11 return [a, b]
12 parent[ra] = rb
13 return []
STEP 1 OF 4Setup

Everyone starts alone

Each node is its own root. Index 0 is unused because nodes are numbered from 1.

VARIABLES

edge
-
parent[1..3]
1, 2, 3
02

Intuition & complexity

The core mental model, trade-offs, and Big-O cost.

What it is

Union-Find (disjoint set union) keeps a parent pointer for every element. find returns a group’s root; union links two roots. Path compression and union by rank keep the trees flat.

Why it matters

Connectivity questions on a growing set of edges - “are these two connected yet?” - are answered in nearly O(1) each.

Think of it like this

Friend groups with one leader each: to check whether two people share a group, compare their leaders.

Use it when

  • Connectivity as edges are added one by one
  • Counting components
  • Finding a redundant edge (a cycle) in an undirected graph

Avoid it when

  • Edges are removed over time - union-find can’t split groups
  • You need the actual path, not just connectivity

Complexity cheatsheet

OperationTimeSpace
find or union, with both optimizationsO(α(n)) amortizedO(n)
Without optimizationsO(n) worst caseO(n)
Process E edgesO(E · α(n))O(n)

Often confused with: BFS or DFS - they answer connectivity too, but rebuild from scratch after every new edge.

03

How to recognize it

Clues in interview prompts that point straight to this pattern.

connected componentsredundant connectiongroupsmerge accountsequal relationships
  • Edges arriving one by one with connectivity queries suggest union-find
  • Kruskal’s minimum spanning tree is built on it
04

Mistakes & edge cases

Catch common off-by-one bugs and corner cases before submitting.

Common mistakes

  • Linking a and b directly instead of their roots
  • Skipping path compression - find degrades to O(n)
  • Off-by-one errors when nodes are numbered from 1

Edge cases to test

  • A self-loop edge [x, x]
  • Nodes numbered from 1 vs 0
  • Every edge already inside one group
Interview tip: Name both optimizations - path compression and union by rank - even if you only code one. This code uses path halving.
05

Knowledge check

Quick check to lock in the intuition.

Question 1 of 3

Why union the two roots instead of the two nodes?

06

Practice

Apply what you just watched on real interview problems.

Generate Graph Theory problem in AI DSA Practice →
  • BeginnerFind if Path Exists in GraphLeetCode 1971 ↗ (opens in a new tab)
  • IntermediateRedundant ConnectionLeetCode 684 ↗ (opens in a new tab)
  • AdvancedAccounts MergeLeetCode 721 ↗ (opens in a new tab)
Topological SortingShortest Path Algorithms