55. Find if Path Exists in Graph
An undirected graph has n vertices labelled 0..n−1 and the given edges. Return whether there is a path from source to destination.
Example 1
Input:
n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2Output:
trueExample 2
Input:
n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5Output:
falseHint 1
Build an adjacency list, then BFS or DFS from the source.
Approach 1: BFS / DFS
Explore from source with a visited set.
⏱ Time O(V + E)💾 Space O(V + E)
Approach 2: Union-Find ✅
Union every edge, then compare roots.
⏱ Time O(E · α)💾 Space O(V)
Reference solution for Union-Find (time O(E · α), space O(V)). Each solution passes every test in all four languages.
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
adj = defaultdict(list)
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
seen, q = {source}, deque([source])
while q: # BFS
u = q.popleft()
if u == destination:
return True
for v in adj[u]:
if v not in seen:
seen.add(v)
q.append(v)
return Falseclass Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
boolean[] seen = new boolean[n];
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(source); seen[source] = true;
while (!q.isEmpty()) { // BFS
int u = q.poll();
if (u == destination) return true;
for (int v : adj.get(u)) if (!seen[v]) { seen[v] = true; q.add(v); }
}
return false;
}
}class Solution {
public:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>> adj(n);
for (auto& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
vector<bool> seen(n, false);
queue<int> q;
q.push(source); seen[source] = true;
while (!q.empty()) { // BFS
int u = q.front(); q.pop();
if (u == destination) return true;
for (int v : adj[u]) if (!seen[v]) { seen[v] = true; q.push(v); }
}
return false;
}
};function validPath(n, edges, source, destination) {
const adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) { adj[a].push(b); adj[b].push(a); }
const seen = new Array(n).fill(false), q = [source];
seen[source] = true;
for (let h = 0; h < q.length; h++) { // BFS
const u = q[h];
if (u === destination) return true;
for (const v of adj[u]) if (!seen[v]) { seen[v] = true; q.push(v); }
}
return false;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Graphs: BFS & DFS.
Run your code to see results here.