Find if Path Exists in Graph (LeetCode 1971): Solution and Explanation
An undirected graph has n vertices labeled 0 to n - 1 and a list of edges. Decide whether destination can be reached from source by following edges.
Intuition
A path from source to destination exists exactly when both vertices sit in the same connected component. So the question is: what can source reach?
Breadth-first search answers that by spreading out from source in rings: first its neighbors, then their neighbors, and so on. Every vertex the search touches is reachable, and every reachable vertex is eventually touched.
The edge list is awkward for this, because finding a vertex's neighbors would mean scanning every edge. Converting it to an adjacency list first makes each neighbor lookup direct.
Mark a vertex as seen the moment it enters the queue. Without that, cycles like 0 - 1 - 2 - 0 would put the same vertex in the queue again and again.
Approach: Breadth-first search
- Build
graph, an adjacency list where each edge[u, v]is added asvingraph[u]anduingraph[v]. - Mark
sourceas seen and put it in a queue. - Pop the front vertex. If it is
destination, return true. - Otherwise queue every neighbor that has not been seen yet, marking each as seen.
- If the queue runs out,
destinationwas never reached: return false.
Step-by-step example
n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
- Adjacency list: 0 -> [1, 2], 1 -> [0, 2], 2 -> [1, 0].
- Seen = {0}, queue = [0].
- Pop 0. It is not 2. Neighbors 1 and 2 are new, so seen = {0, 1, 2} and queue = [1, 2].
- Pop 1. It is not 2. Its neighbors 0 and 2 are already seen, so nothing is added.
- Pop 2. It is the destination, so return true.
Code: Python, Java, C++
1class Solution:
2 def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
3 graph = [[] for _ in range(n)]
4 for u, v in edges:
5 graph[u].append(v)
6 graph[v].append(u)
7 seen = {source}
8 queue = deque([source])
9 while queue:
10 node = queue.popleft()
11 if node == destination:
12 return True
13 for nxt in graph[node]:
14 if nxt not in seen:
15 seen.add(nxt)
16 queue.append(nxt)
17 return False1class Solution {
2 public boolean validPath(int n, int[][] edges, int source, int destination) {
3 List<List<Integer>> graph = new ArrayList<>();
4 for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
5 for (int[] e : edges) {
6 graph.get(e[0]).add(e[1]);
7 graph.get(e[1]).add(e[0]);
8 }
9 boolean[] seen = new boolean[n];
10 seen[source] = true;
11 Deque<Integer> queue = new ArrayDeque<>();
12 queue.offer(source);
13 while (!queue.isEmpty()) {
14 int node = queue.poll();
15 if (node == destination) {
16 return true;
17 }
18 for (int nxt : graph.get(node)) {
19 if (!seen[nxt]) {
20 seen[nxt] = true;
21 queue.offer(nxt);
22 }
23 }
24 }
25 return false;
26 }
27}1class Solution {
2public:
3 bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
4 vector<vector<int>> graph(n);
5 for (auto& e : edges) {
6 graph[e[0]].push_back(e[1]);
7 graph[e[1]].push_back(e[0]);
8 }
9 vector<bool> seen(n, false);
10 seen[source] = true;
11 queue<int> q;
12 q.push(source);
13 while (!q.empty()) {
14 int node = q.front();
15 q.pop();
16 if (node == destination) {
17 return true;
18 }
19 for (int nxt : graph[node]) {
20 if (!seen[nxt]) {
21 seen[nxt] = true;
22 q.push(nxt);
23 }
24 }
25 }
26 return false;
27 }
28};Time and space complexity
O(n + e)
Building the adjacency list touches each edge once, and the search pops each vertex at most once and scans each adjacency entry at most once.
O(n + e)
The adjacency list holds 2e entries, and the seen set and queue hold up to n vertices.
Other approaches
Union-Find (time O(e * α(n)), space O(n))
Union the two endpoints of every edge, then check whether source and destination have the same root. No adjacency list is needed, and with path compression and union by rank it is nearly linear.
Depth-first search (time O(n + e), space O(n + e))
Explore from source with an explicit stack or recursion instead of a queue. It reaches the same set of vertices. Recursion can overflow the call stack on a long chain of 200,000 vertices, so an explicit stack is safer.
Common mistakes
- Storing each edge in only one direction. The graph is undirected, so both endpoints need the other in their neighbor list.
- Marking vertices as seen when they are popped instead of when they are pushed. The answer stays correct, but a vertex can be queued many times, which can blow up time and memory on dense graphs.
- Forgetting the case source == destination. The path of length zero counts, so the answer is true even with no edges.
- Deep recursion in DFS on a long path graph, which can exceed the recursion limit in Python.
Frequently asked questions
BFS or DFS: which is better here?
Either is fine because we only need reachability, not the shortest path. BFS with a queue avoids recursion limits, which matters when the graph is one long chain.
Why stop as soon as the destination is popped?
Being popped means it was reached from source through a chain of edges. Nothing else the search might find can change the answer, so continuing would only waste time.
When would Union-Find be the better choice?
When you need to answer many reachability questions on the same graph, or edges arrive over time. After the unions, each query is just two root lookups.