Find if Path Exists in Graph

BFS/DFS or Union-Find to check connectivity between two nodes in an undirected graph.

Easy
Time O(N + E) Space O(N + E)
LeetCode
3 min read
union-find bfs graph

Problem#

Given a bi-directional graph with n nodes and edge list edges, return true iff there is a path from source to destination.

Examples#

  • n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2true.
  • n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5false.

Constraints#

  • 1 <= n <= 2 * 10^5, 0 <= edges.length <= 2 * 10^5.

Hints#

Hint
DSU is the simplest: union edges, then check whether source and destination share a root.

Approach#

Build DSU; union every edge. Return find(source) == find(destination).

Solution#

Find if Path Exists in Graph
class Solution {
vector<int> parent;
int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
void unite(int a, int b) { parent[find(a)] = find(b); }
public:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
parent.resize(n);
iota(parent.begin(), parent.end(), 0);
for (auto& e : edges) unite(e[0], e[1]);
return find(source) == find(destination);
}
};

Editorial#

Connectivity is the defining DSU primitive. After unioning all edges, two nodes share a path iff they share a component root. BFS/DFS works equally well but allocates per-query traversal state; DSU answers all “are these connected?” queries in O(α) after a single O(E) build.

Complexity#

  • Time: O(N + E * α(N)).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.