← Visualizers
Traversal · 1.E · Undirected Reachability LeetCode 1971

Find if Path Exists in Graph / visualized

Given an undirected graph of n vertices and bidirectional edges. Determine whether there is a valid path from source to destination.

Breadth-First Search Wave

idle
INVARIANT Path Connectivity Invariant: Launch BFS or DFS from source. Enqueue neighbors with mark-on-push to prevent cycles. If the current or neighboring node matches destination, terminate immediately (early exit: true). If queue drains without reaching destination, return false.
Queue:[]
Current:-
Visited:[]
Press Run to begin.
0 / 0

Java 21 Solution

INTERVIEW SCRIPT

How to Explain Path Exists in Graph to an Interviewer

1. Trivial Base Cases First

"If source == destination, we are already at the target—return true immediately in $O(1)$ time."

2. Adjacency Representation

"Convert the edge list into an adjacency list: List<Integer>[] g. Since edges are bi-directional, add each edge in both directions."

3. BFS with Mark-on-Push

"Seed a queue with source and mark visited[source] = true. While queue is non-empty, poll u. For each neighbor v, if v == destination, return true immediately. Otherwise mark visited[v] = true and enqueue."

4. BFS vs Disjoint Set Union (DSU)

"Both BFS and DSU solve this problem effectively: BFS takes $O(V + E)$ time and space; DSU takes $O(E \cdot \alpha(V))$ and is optimal when handling multiple dynamic connectivity queries."

O(V + E) time · O(V + E) space · BFS reachability with early exit · Dual granularity navigation