← Graph Exploration

Micro-Drill #222 — Union-Find vs BFS/DFS for components

Graph Exploration Target: 15s

Union-Find excels at dynamic connectivity queries. BFS/DFS excels at traversal and shortest paths. Different tools for different jobs.

UNION-FIND vs BFS/DFS FOR COMPONENTS
─────────────────────────────────────
BFS/DFS:                        UNION-FIND:
  One-shot traversal              Online / streaming edges
  O(V + E) per query              O(α(n)) ≈ O(1) per operation
  Need adjacency list             Works with edge list directly
  Simpler code                    Better for dynamic connectivity

USE UNION-FIND when:
  □ Edges arrive one at a time
  □ "Are X and Y connected?" queries
  □ Need to merge groups repeatedly
  □ Kruskal's MST algorithm
  □ Count components as edges added
  Examples: redundant connection, accounts merge

USE BFS/DFS when:
  □ Need to traverse/visit nodes in order
  □ Need shortest path
  □ Graph already built as adjacency list
  □ Need to process each component's nodes
  Examples: number of islands, clone graph

HYBRID: use Union-Find to detect components,
        then BFS/DFS within each component

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #221 Micro #223 →