Find if Path Exists in Graph
Easy
Topics
There is a bi-directional graph with n vertices labeled 0..n-1, described by the list of undirected edges. Return true if there is a valid path from vertex 0 to vertex n-1, and false otherwise.
Example 1
true.Input: n = 3, edges = [[0,1],[1,2],[2,0]] Output: true
Example 2
false.Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]] Output: false
Constraints
- 1 <= n <= 2*10^5
- 0 <= edges.length <= 2*10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
We only need to know whether two vertices are in the same connected component. A BFS or DFS from the source answers it in O(n + e) and is the obvious approach.
Union-Find answers a slightly different and more general question: it maintains the components as edges arrive, so it can answer "same component?" for any pair, repeatedly, without re-traversing. For a single query the two are equivalent in cost; the reason to reach for Union-Find is that it extends to a stream of edges and a stream of queries, which a traversal does not.
The structure is a parent array where each vertex points toward a representative. Two vertices are connected exactly when they resolve to the same representative.
💡 Path compression: par[x] = par[par[x]] during the walk flattens the chain as a side effect of looking something up, so repeated queries get progressively cheaper. Combined with union-by-rank this gives near-constant amortised cost; with compression alone, as here, it is still effectively flat for these sizes.
Approach
par[i] = ifor every vertex.find(x)walks to the representative, halving the path on the way.- For each edge, point one representative at the other.
- Return whether
find(source)equalsfind(destination).
Dry Run
n = 3, edges = [[0,1],[1,2]]
init par = [0,1,2]
edge (0,1) find(0)=0, find(1)=1 -> par[0]=1 par = [1,1,2]
edge (1,2) find(1)=1, find(2)=2 -> par[1]=2 par = [1,2,2]
find(0): par[0]=1 -> par[1]=2 -> 2
find(2): 2
equal -> trueComplexity
- Time — O(n + e) effectively: initialisation is O(n), and each of the
eunions does two near-constant finds. The precise bound with path compression alone is O(log n) amortised per operation; adding union-by-rank reduces it to inverse-Ackermann, which is constant for any realisticn. - Space — O(n): the parent array. A BFS needs the same for its visited set plus a queue.
Common Pitfalls
- Writing
par[a] = binstead ofpar[find(a)] = find(b). Linking the vertices rather than their representatives silently splits components. - Recursive
findon 2*10^5 vertices. A degenerate chain overflows the stack before compression has a chance to flatten it; the iterative loop here avoids that. - Returning early inside the edge loop. All edges must be processed before any query, since a later edge can connect the two.
- Handling
source == destinationas a special case. It falls out: a vertex is always its own representative. - Assuming the graph is connected, or that edges are sorted. Neither is promised.
Full Solution — all languages
class Solution:
def validPath(self, n, edges):
par = list(range(n))
def find(x):
while par[x] != x:
par[x] = par[par[x]]; x = par[x]
return x
for a, b in edges:
par[find(a)] = find(b)
return find(0) == find(n - 1)import java.util.*;
class Solution {
public boolean validPath(int n, int[][] edges) {
int[] par = new int[n];
for (int i = 0; i < n; i++) par[i] = i;
for (int[] e : edges) par[find(par, e[0])] = find(par, e[1]);
return find(par, 0) == find(par, n - 1);
}
int find(int[] par, int x) {
while (par[x] != x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool validPath(int n, vector<vector<int>>& edges) {
vector<int> par(n);
for (int i = 0; i < n; i++) par[i] = i;
function<int(int)> find = [&](int x) {
while (par[x] != x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
};
for (auto& e : edges) par[find(e[0])] = find(e[1]);
return find(0) == find(n - 1);
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/ var validPath = function(n, edges) {
const par = [];
for (let i = 0; i < n; i++) par[i] = i;
const find = (x) => {
while (par[x] !== x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
};
for (const [a, b] of edges) par[find(a)] = find(b);
return find(0) === find(n - 1);
};