DSA AnimatorDSA animations
Find if Path Exists in Graph LC #1971 Easy Graph · Union-Find
Problem

There is a bi-directional graph with n vertices labeled 0 to n-1. Given source and destination, return true if there is a valid path from source to destination.

Example 1
Input: n=3, edges=[[0,1],[1,2],[2,0]], source=0, destination=2
Output: true
Try Examples
Custom: n / edges (a-b) / src / dst
Approach
Union-Find (Disjoint Set Union)
Each node starts as its own parent. union(a,b) connects components. Path exists iff find(src) == find(dst) (same component).
Graph & Parent Array
Load an example to begin.
Variables
Edge
—
find(a)
—
find(b)
—
parent[]
—
Step Logic
Press ▶ Play or Next Step to begin.
✓
Ready
0 / 0
Select an example and press Play.
Algorithm
1
Initialize parent[i]=i for all nodes
2
For each edge (a,b): union(parent, a, b)
3
Path exists iff find(parent,src)==find(parent,dst)
Time
O(n·α(n))
Space
O(n)
Why Union-Find

Union-Find tracks connected components. After processing all edges, src and dst are in the same component iff they're connected. Path compression makes lookups near O(1).

How to solve Find if Path Exists in Graph

LeetCode 1971 · Easy · Graph · Pattern: BFS / Union Find

Why the obvious approach is slow

Trying every possible path from the source can blow up on graphs with many cycles. We only need to know whether the destination is reachable, not the path itself.

The key idea

First, turn the edge list into an adjacency list, so each node knows its neighbours. Then run a breadth first search from the source. Mark a node as visited when you add it to the queue, so no node is processed twice. If the destination is ever visited, the answer is true. If the queue runs empty first, the answer is false.

Remember

Reachability is a plain BFS or DFS with a visited set. Union find answers the same question by checking if both nodes share a root.

Run the animation above on your own input, or watch the 2:00 video explanation of Find if Path Exists in Graph with a dry run and Java code.

More Graph problems