Find if Path Exists in Graph easy
Description
There’s a bidirectional graph with n nodes labeled 0 through n - 1. You’re given a 2D array edges and two integers source and destination. Return true if there’s a path from source to destination — false otherwise.
Examples
> Case 1:
Input: n = 3, edges = [[0, 1], [1, 2], [2, 0]], source = 0, destination = 2
Output: true # 0 → 1 → 2 (or 0 → 2 directly)
> Case 2:
Input: n = 6, edges = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]],
source = 0, destination = 5
Output: false # 0's component is {0, 1, 2}; 5 is in {3, 4, 5}Constraints
1 <= n <= 2 · 10^50 <= edges.length <= 2 · 10^5- The graph is undirected and may not be connected.
Three approaches, all O(V + E)
Reachability has three classic answers:
- BFS — explore layer by layer with a queue. Natural for “is there any path” or “shortest path on an unweighted graph.”
- DFS — go deep with a stack (or recursion). Equally good for reachability, sometimes uses less code.
- Union-Find (DSU) — preprocess by merging nodes that share an edge into the same group; then check if source and destination are in the same group.
All three are O(V + E) for one query. Union-Find shines when you have many queries on the same graph — preprocess once, query each pair in nearly O(1).
We’ll implement all three so you can pick the one that reads cleanest in your head.
Approach 1: BFS
Approach 2: DFS (iterative — to dodge stack overflow on big graphs)
Approach 3: Union-Find
If you only have one query, Union-Find is overkill. But it’s the fastest when you have many queries, and it’s a nice exercise.
Union-Find is the gateway to many graph algorithms — Kruskal’s MST, network connectivity, dynamic connectivity. We’ll cover it formally on Day 20. For now, the two-method API (find + union) is enough to solve dozens of problems.
Analysis
| Approach | Time per query | Pre-processing | Space |
|---|---|---|---|
| BFS / DFS | O(V + E) | None | O(V + E) |
| Union-Find | ~O(1) per query | O(V + E α(V)) | O(V) |
Where α(V) is the inverse Ackermann function — effectively a small constant for any realistic input.