LeetCode #1971 Easy

Find if Path Exists in Graph

Find if Path Exists in Graph is LeetCode 1971 (Easy). A graph has n vertices labelled 0 to n - 1, and each pair [u, v] in edges is an undirected edge. Return true if some path connects source to destination, and false otherwise.

  • There are no duplicate edges and no edge from a vertex to itself.
  • Only whether a path exists matters, not how long it is.

With up to 2 × 10⁵ vertices and edges, the search must be linear in their total.

Constraints
  • 1 <= n <= 2 * 10⁵
  • 0 <= edges.length <= 2 * 10⁵
  • edges[i].length == 2
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 0 <= source, destination <= n - 1
  • There are no duplicate edges.
  • There are no self edges.
graphdfsbfsunion-find
Open on LeetCode ↗
02

Intuition

Start at source and mark every vertex you can reach. The answer is true exactly when destination gets marked. Any search that visits each reachable vertex once will do; this one uses a stack.

  • Only reachable vertices get marked: a vertex is pushed only from a neighbour that was itself reached.
  • Every reachable vertex gets marked: follow any path from source. If some vertex on it stayed unmarked, the vertex just before it was marked and popped, and popping it would have pushed its neighbour. So no vertex on the path is missed.
How to spot this pattern

"Can I get from A to B?" with no weights is plain reachability: one DFS or BFS from A, or union-find over the edges. Number of Provinces, Keys and Rooms and flood-fill grid problems are this same marking walk.

03

Approach

Try it first

Before reading on: with n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0 and destination = 5, list the vertices a search from 0 can mark. What tells the search it can stop and answer false?

1

Build an undirected adjacency list

Make n empty lists. For each pair [u, v], append v to adj[u] and u to adj[v], because an undirected edge can be walked from either end. The search then finds a vertex's neighbours without scanning the edge list.

2

Mark the source and push it

Set seen[source] = True and start the stack as [source]. Marking it now means no neighbour can push it back later. If source == destination, the very first pop finds the answer, so that case needs no special code.

3

Pop a vertex and compare it with the destination

Pop u from the stack. If u == destination, return true right away: a path exists, and the rest of the stack does not matter.

4

Push every neighbour not yet seen

For each v in adj[u] with seen[v] still false, set seen[v] = True and push v. Marking at push time means each vertex enters the stack at most once, which keeps the work at one visit per vertex and two checks per edge.

5

Return false when the stack is empty

An empty stack means every vertex reachable from source has been popped and none was the destination. The destination lies in another piece of the graph, so no path exists.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def validPath(self, n, edges, source, destination):
▶3 adj = [[] for _ in range(n)]
▶4 for u, v in edges:
▶5 adj[u].append(v)
▶6 adj[v].append(u)
▶7 
▶8 seen = [False] * n
▶9 seen[source] = True
▶10 stack = [source]
▶11 while stack:
▶12 u = stack.pop()
▶13 if u == destination:
▶14 return True
▶15 for v in adj[u]:
▶16 if not seen[v]:
▶17 seen[v] = True
▶18 stack.append(v)
▶19 return False
0S12Dneighbours012102210seen012stack (top on the right)empty3 edges → each added both ways
n3
edges3
Each pair [u, v] is a road that works in both directions, so v goes into u's list and u into v's list. The lists on the right are what the search reads; the edge pairs themselves are not looked at again.
0S12Dneighbours012102210seen✓012stack (top on the right)0push source 0 and mark it seen
stack[0]
seen{0}
The search starts from the source, vertex 0. It is marked seen as it goes on the stack, so no neighbour can push it a second time.
0S12Dneighbours012102210seen✓012stack (top on the right)emptypop 0 → not the destination
u0
stack[]
Pop 0. It is not 2, so its neighbours are checked next: 1, 2.
0S12Dneighbours012102210seen✓0✓12stack (top on the right)11 is new → mark it, push it
v1
stack[1]
Vertex 1 has not been seen. Mark it now, at push time, so another neighbour cannot push it too, then put it on the stack.
0S12Dneighbours012102210seen✓0✓1✓2stack (top on the right)122 is new → mark it, push it
v2
stack[1, 2]
Vertex 2 has not been seen. Mark it now, at push time, so another neighbour cannot push it too, then put it on the stack.
0S12Dneighbours012102210seen✓0✓1✓2stack (top on the right)1popped 2 = destination → true
u2
resulttrue
Vertex 2 is the destination, so a path exists and the search stops at once. The green edges show the route it followed: 0 → 2. Vertices still on the stack are never needed.
05

Common pitfalls

Adding each edge in one direction only

✗ Wrong
for u, v in edges:
    adj[u].append(v)
✓ Right
for u, v in edges:
    adj[u].append(v)
    adj[v].append(u)

With n = 2, edges = [[1, 0]], source = 0, destination = 1, vertex 0 gets no neighbours, the stack empties after one pop and the answer comes out false. The edge works both ways, so the answer is true.

Recursive DFS on a long chain

✗ Wrong
def dfs(u):
    seen[u] = True
    return u == destination or any(
        dfs(v) for v in adj[u] if not seen[v])
✓ Right
stack = [source]
while stack:
    u = stack.pop()

For edges = [[0,1], [1,2], ..., [199998,199999]] with source = 0 and destination = 199999, each call waits on the next, 2 × 10⁵ deep. Python raises RecursionError at about 1,000, and raising the limit that far can crash the interpreter. An explicit stack has no depth limit.

Using an adjacency matrix

✗ Wrong
adj = [[False] * n for _ in range(n)]
✓ Right
adj = [[] for _ in range(n)]

At n = 2 × 10⁵ the matrix has 4 × 10¹⁰ cells, far beyond the memory limit, and scanning a row to find neighbours costs O(n) per vertex. Lists store only the 2 × 10⁵ edges that exist.

06

Edge cases

source == destination, for example n = 1, edges = []

The source is pushed and then popped as the first vertex, it equals the destination, and the answer is true without reading any edge.

07

Complexity

Time
O(V + E)
Space
O(V + E)
V is n and E is the number of edges. Building the lists touches each edge twice; each vertex is pushed and popped at most once. The lists hold 2E entries, and seen and the stack hold at most V.
08

Find if Path Exists in Graph FAQ

Should this use DFS, BFS or union-find?

All three pass. BFS is this code with a queue in place of the stack. Union-find joins the two ends of every edge and then checks whether source and destination have the same root; it needs no adjacency list and pays off when many source and destination pairs are asked about one fixed graph. For a single question, the stack search is the simplest.

Why mark a vertex when it is pushed instead of when it is popped?

Marking on pop still gives the right answer, but a vertex can then be pushed once by every neighbour before it is popped. In a graph where one vertex links to every other and they all link to each other, the stack can grow to about E entries instead of at most V. Marking on push caps it at V.