Union Find
Master this topic with zero to advance depth.
Number of Islands
Given an 2D binary grid, return the number of islands. An island is surrounded by water and is formed by connecting adjacent land cells horizontally or vertically.
Examples
Level I: DFS (Matrix Traversal)
Intuition
Traverse the grid. When we find '1' (land), increment the island count and use DFS to mark all connected land as '0' (visited).
Detailed Dry Run
Found '1' at (0,0). Increment count. DFS marks (0,1), (1,0), (1,1) as '0'. Continue.
Level III: Union-Find (Grid Logic)
Intuition
Treat each land cell as a node in a DSU. For every '1', union it with its neighbors. The number of islands is the number of land cells minus successful unions.
Detailed Dry Run
Total '1's = 5. Union (0,0) and (0,1) -> success, count becomes 4. Union (0,0) and (1,0) -> success, count becomes 3.
Graph Valid Tree
Given nodes and a list of undirected edges, determine if these edges form a valid tree. A tree is a connected graph with no cycles.
Level I: BFS (Connectivity & Reachability)
Intuition
A graph is a tree if it has exactly edges and all nodes are connected. Check edge count first, then use BFS to ensure all nodes are reachable from node 0.
Detailed Dry Run
n=5, edges=4. Correct. Start BFS from 0. Visit 1, 2, 3. From 1 visit 4. Visited size = 5. True.
Level III: Union-Find (Cycle Detection)
Intuition
Use DSU to process edges. If an edge connects two nodes already in the same component, a cycle exists. If no cycles and edges = , it's a tree.
Detailed Dry Run
Edge [0,1]: Union(0,1). Edge [0,2]: Union(0,2). Edge [1,2]: Find(1)=0, Find(2)=0. Same root! Cycle! False.
Number of Provinces
Given an matrix isConnected where isConnected[i][j] = 1 if city and city are directly connected. Return the total number of provinces (connected components).
Examples
Level I: DFS (Component Counting)
Intuition
Treat the matrix as an adjacency list. For each city, if not visited, start a DFS to visit all cities in its province. Count the number of DFS starts.
Detailed Dry Run
City 0: unvisited. Count=1. DFS(0) visits City 1. City 1: visited. City 2: unvisited. Count=2. DFS(2).
Level III: Union-Find (Component ID)
Intuition
Standard DSU application. For every connection, perform a union. The answer is the initial city count minus successful unions.
Detailed Dry Run
3 Cities. Initial count=3. Union(0,1) -> success, count=2. Connection(0,2)=0 -> no union. Connection(1,2)=0 -> no union.
Accounts Merge
Given a list of accounts where each element accounts[i] is a list of strings, the first element accounts[i][0] is a name, and the rest are emails. Merge accounts belonging to the same person. Two accounts belong to the same person if there is some common email to both accounts.
Examples
Level I: DFS (Graph of Emails)
Intuition
Build an adjacency list where each email is a node and edges connect emails within the same account. Use DFS to find connected components of emails.
Detailed Dry Run
Account 1: {a, b}. Account 2: {c, a}. Graph: a-b, c-a. Component: {a, b, c}. Sort and add name 'John'.
Level III: Union-Find (Email Mapping)
Intuition
Use DSU to union all emails within an account. After processing all accounts, group emails by their root parent, sort them, and format the output.
Detailed Dry Run
Initial: {a:a, b:b, c:c}. Account 1: Union(a, b) -> {a:b, b:b}. Account 2: Union(c, a) -> {c:b, a:b}. All point to 'b'.
Redundant Connection
In this problem, a tree (undirected graph with no cycles) was modified by adding one extra edge. Return the edge that can be removed so the resulting graph is a tree.
Examples
Level I: DFS (Incremental Cycles)
Intuition
For each new edge , check if is already reachable from . If yes, this edge forms a cycle and is redundant.
Detailed Dry Run
Edge [1,2]: Added. Edge [1,3]: Added. Edge [2,3]: DFS(2) finds 3 via 1. Redundant!
Level III: Union-Find (Efficiency)
Intuition
Use DSU to process edges. If an edge connects two nodes that already share the same root, that edge is the redundant one.
Detailed Dry Run
Edge [1,2]: Union(1,2). Edge [1,3]: Union(1,3). Edge [2,3]: find(2)=3, find(3)=3. Same component. Return [2,3].
Number of Connected Components
Given nodes and a list of undirected edges, return the number of connected components.
Examples
Level I: DFS (Graph Traversal)
Intuition
Build an adjacency list. Perform DFS starting from each unvisited node. Each start represents a new component.
Detailed Dry Run
Start DFS(0): visits 1, 2. Count=1. Start DFS(3): visits 4. Count=2.
Level III: Union-Find (Direct)
Intuition
Start with components. For each edge, perform a union if the nodes are in different components and decrement the count.
Detailed Dry Run
n=5. [0,1]: Union count=4. [1,2]: Union count=3. [3,4]: Union count=2. Result = 2.
Satisfiability of Equality Equations
Given equations like 'a==b' or 'b!=a', check if it's possible to satisfy all equations.
Examples
Level III: Union-Find (Double Pass)
Intuition
Pass 1: Process all '==' and union symbols into components. Pass 2: Process all '!=' and check if the symbols already share a root. If they do, it's a contradiction.
Detailed Dry Run
a==b (Union a,b). b==c (Union b,c). a!=c (Find a=c, Find c=c. Conflict!).
Most Stones Removed
On a 2D plane, return the largest number of stones that can be removed. A stone can be removed if it shares a row or column with another stone.
Examples
Level I: DFS (Component Counting)
Intuition
Represent stones as nodes and connect them if they share a row/column. Total stones - Number of components = Max stones removed.
Detailed Dry Run
6 stones. DFS finds 1 connected component. 6 - 1 = 5.
Level III: Union-Find (Row-Column Mapping)
Intuition
Treat rows and columns as nodes. For each stone (r, c), union row r with column c. The number of stones removed is (Total Stones - Number of components).
Detailed Dry Run
Stone (0, 0): Union row 0 with column 10001 (offset to distinguish).
Smallest String With Swaps
Given a string s and pairs of indices that can be swapped, return the lexicographically smallest string possible.
Examples
Level III: Union-Find + Sorting (Optimal)
Intuition
Indices that can swap form connected components. All characters within a component can be moved to any index in that component. Sort characters for each component and place them in sorted index order.
Detailed Dry Run
Indices {0, 3} are connected. Characters are s[0]='d', s[3]='b'. Sorted: 'b', 'd'. Place 'b' at index 0 and 'd' at index 3.
Bricks Falling When Hit
You are given an binary grid where 1 represents a brick. A brick will not fall if it is connected to the top row (row index 0) or another brick that will not fall. When a brick is 'hit', it turns into 0. Return the number of bricks that fall after each hit.
Reverse Union-Find Strategy
- Remove all hit bricks first.
- Build the initial graph for the remaining bricks.
- Add hit bricks back in reverse order.
- The number of new bricks connected to the top row (excluding the re-added brick itself) is the number of falling bricks for that hit.
Examples
Level II: BFS (Exhaustive Simulation)
Intuition
This approach directly simulates the process for each hit. After removing a brick, we perform a broad connectivity check (using BFS/DFS) to see which bricks are still connected to the top row. Any brick that was previously connected but is no longer is counted as 'fallen'.
Level III: Reverse DSU (Connectivity Recovery)
Intuition
Tracking 'falling' bricks is hard. Tracking 'recovered' bricks by adding them back in reverse is much easier. Use a dummy node to represent the 'ceiling' (connected to all row 0 bricks).
Redundant Connection II
In this problem, a rooted tree is modified by adding exactly one extra edge. The extra edge is directed from parent to child. The resulting graph can have two issues:
- A node has two parents.
- There is a directed cycle.
Strategy
- Check if any node has two parents.
- If yes, test if removing the second edge fixes everything. If not, the first edge was the problem.
- If no node has two parents, simply find the edge that completes a cycle using Union-Find (like Redundant Connection I).
Examples
Level I: DFS (Recursive Search)
Intuition
This problem involves finding an edge whose removal leaves a rooted tree. We can try removing each edge one by one and check if the resulting graph is a valid rooted tree (all nodes reachable from a single root, no cycles) using DFS.
Level III: Union-Find + Case Analysis
Intuition
Handle two cases: Case 1 is a node having two parents (two edges pointing to it). Case 2 is a simple cycle. Use DSU to detect which edge completes a cycle after potentially 'skipping' one of the double-parent edges.
Critical Connections in a Network
An edge in an undirected graph is a critical connection (bridge) if removing it increases the number of connected components. Return all such edges.
Relation to DSU
While standard DSU doesn't easily find bridges (Tarjan's or Kosaraju's are preferred), we can use a specialized 2-Edge-Connected Components algorithm using DSU. Any edge that is part of a cycle is NOT critical. We can use DSU to merge nodes in the same cycle.
Examples
Level II: Brute-Force DFS (Bridge Detection)
Intuition
For each connection , remove it from the graph and check if the graph is still connected using DFS. If it's not, the edge is a critical connection.
Level III: Tarjan's Algorithm (Standard)
Intuition
Use DFS discovery time and 'low-link' values. An edge is a bridge if .
Minimum Score of a Path Between Two Cities
You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance distancei. The score of a path between two cities is defined as the minimum distance of a road in this path. Return the minimum possible score of a path between city 1 and city n.
Insight
If cities 1 and n are connected, you can traverse any road in their connected component multiple times. Thus, the answer is simply the minimum weight road in the entire component containing city 1.
Examples
Level I: DFS (Component Traversal)
Intuition
Since we can traverse any road in a connected component multiple times, the path score is simply the minimum weight of any road in the entire component that contains city 1 (and thus city n, if reachable). Use DFS to traverse the component and track the minimum weight encountered.
Level III: Union-Find (Component Min Edge)
Intuition
Use DSU to maintain connected components and store the minimum edge weight seen so far for each component root.
Remove Max Number of Edges to Keep Graph Fully Traversable
Alice and Bob can traverse a graph. There are three types of edges:
- Type 1: Only Alice can traverse.
- Type 2: Only Bob can traverse.
- Type 3: Both can traverse. Return the maximum number of edges you can remove such that both can traverse the entire graph.
Strategy
- Prioritize Type 3 edges: Using one Type 3 edge replaces one Type 1 AND one Type 2 edge.
- Use two DSU instances:
dsuAliceanddsuBob. - After using all potential Type 3 edges, use Type 1 for Alice and Type 2 for Bob.
- If either graph is not connected (components > 1), return -1.
Examples
Level II: BFS (Exhaustive Connectivity)
Intuition
Try removing each edge one by one. After removal, check if both Alice and Bob can still traverse the entire graph using two separate BFS/DFS calls. This is the brute-force way to see which edges are truly redundant.
Level III: Two Union-Finds + Greedy Edge Selection
Intuition
Greedily add common edges (Type 3) first. Then add person-specific edges only if needed for connectivity.
Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
Union-Find Perspective
If nums contains x and x+1, we can Union(x, x+1). The size of the largest component is the answer.
Examples
Level I: Sorting + HashSet
Intuition
Sort the array and then iterate through it, checking if the current number is exactly one greater than the previous one. A HashSet can also be used to query neighbors in time and expand sequences.
Level III: Union-Find (Set Growth)
Intuition
Iterate through each number num. If num+1 exists in the set, union num and num+1. Keep track of the size of each component.
Couples Holding Hands
There are couples sitting in seats. Every couple is assigned IDs . Return the minimum number of swaps so that every couple is sitting side by side.
Mathematical Insight
This is a permutation decomposition problem. If we have couples and they form cycles (connected components of incorrectly paired couples), the number of swaps needed is .
Examples
Level II: Greedy Swaps
Intuition
Iterate through the seats in pairs. For each seat and , if they are not already a couple, find where the partner of the person at seat is sitting and swap them into seat . This local greedy strategy is optimal.
Level III: Union-Find (Cycle Decomposition)
Intuition
Each pair of seats should hold a couple. If seat pair holds parts of couple and couple , union and . The number of swaps is total couples minus number of components.
Regions Cut By Slashes
An grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space. These characters divide the square into contiguous regions. Return the number of regions.
Visualization (4 per cell)
Divide each 1x1 cell into 4 triangles:
/\
/ 0\
<3 1>
\ 2/
\/ - '/' connects 0-3 and 1-2.
- '\' connects 0-1 and 2-3.
- ' ' connects 0-1-2-3.
Examples
Level II: BFS (Grid Expansion)
Intuition
Scale the grid into a binary grid. Map '/' and '\' to sets of 1s in the 3x3 block. Then, use standard BFS or DFS to count connected components of 0s. This is more memory-intensive but conceptually simpler than triangle mapping.
Level III: Union-Find (Internal Grid Mapping)
Intuition
Represent each cell by 4 distinct nodes. Union neighboring triangles within the same cell based on the character ('/', '\', or ' '). Then, union adjacent triangles of neighboring cells. The final component count is the number of regions.
Minimize Malware Spread
In a network of nodes, some nodes are initially infected with malware. Malware spreads through connected components. You can remove exactly one node from the initial list to minimize total infected nodes. If multiple nodes lead to the same result, return the node with the smallest index.
Optimization Strategy
Only removing an infected node in a component with exactly one initially infected node will actually reduce the total infection (by the size of that component).
Examples
Level II: DFS (Component Analysis)
Intuition
Use DFS to find all connected components in the graph. For each component, count how many nodes in initial are part of it. If only one node is infected, removing it saves all nodes in that component. Track the best node to remove.
Level III: Union-Find (Component Size Analysis)
Intuition
Build components using Union-Find and record the size of each. For each component, count how many nodes from initial are in it. If a component has exactly one initial node, moving that node saves size nodes. Pick the one that saves the most.
Making a Large Island
Change at most one 0 to 1 in a binary grid to get the largest possible island.
Examples
Level III: Union-Find (Component Sizes)
Intuition
Pre-calculate all island sizes using DSU. Then, for each '0', calculate the potential island size by summing sizes of all unique neighbor islands + 1.
Detailed Dry Run
Grid: [[1,0],[0,1]]. DSU islands: {0}:sz=1, {3}:sz=1. Flip (0,1) at index 1: Neighbors indices 0 and 3 are in different islands. Total: 1+1+1 = 3.
Swim in Rising Water
Find the minimum time t needed to reach the bottom-right from the top-left in a grid with elevations.
Examples
Level III: Union-Find (Threshold Connectivity)
Intuition
Sort all cells by elevation. Add cells to DSU one by one in increasing order of (elevation). Stop when top-left and bottom-right are in the same component.
Detailed Dry Run
Cells sorted by elevation: (0,0):0, (1,0):1, (0,1):2, (1,1):3. At t=3, (1,1) is added, connecting everything. Result=3.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.