Find if Path Exists in Graph

Easy

Topics
GraphDFSBFSUnion Find

There is a bi-directional graph with n vertices labeled 0..n-1, described by the list of undirected edges. Return true if there is a valid path from vertex 0 to vertex n-1, and false otherwise.

Example 1

012
source and destination
The question is only whether the two shaded nodes sit in the same component. Here they are connected, so true.
Nodes are drawn on a circle; an edge list says nothing about layout, only about connections.
Input:  n = 3, edges = [[0,1],[1,2],[2,0]]
Output: true

Example 2

012345
source and destination
Here they are in different components, so false.
Input:  n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]]
Output: false

Constraints

  • 1 <= n <= 2*10^5
  • 0 <= edges.length <= 2*10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

We only need to know whether two vertices are in the same connected component. A BFS or DFS from the source answers it in O(n + e) and is the obvious approach.

Union-Find answers a slightly different and more general question: it maintains the components as edges arrive, so it can answer "same component?" for any pair, repeatedly, without re-traversing. For a single query the two are equivalent in cost; the reason to reach for Union-Find is that it extends to a stream of edges and a stream of queries, which a traversal does not.

The structure is a parent array where each vertex points toward a representative. Two vertices are connected exactly when they resolve to the same representative.

💡 Path compression: par[x] = par[par[x]] during the walk flattens the chain as a side effect of looking something up, so repeated queries get progressively cheaper. Combined with union-by-rank this gives near-constant amortised cost; with compression alone, as here, it is still effectively flat for these sizes.

Approach

  1. par[i] = i for every vertex.
  2. find(x) walks to the representative, halving the path on the way.
  3. For each edge, point one representative at the other.
  4. Return whether find(source) equals find(destination).

Dry Run

n = 3, edges = [[0,1],[1,2]]

init        par = [0,1,2]
edge (0,1)  find(0)=0, find(1)=1 -> par[0]=1      par = [1,1,2]
edge (1,2)  find(1)=1, find(2)=2 -> par[1]=2      par = [1,2,2]

find(0): par[0]=1 -> par[1]=2 -> 2
find(2): 2
equal -> true

Complexity

  • Time — O(n + e) effectively: initialisation is O(n), and each of the e unions does two near-constant finds. The precise bound with path compression alone is O(log n) amortised per operation; adding union-by-rank reduces it to inverse-Ackermann, which is constant for any realistic n.
  • Space — O(n): the parent array. A BFS needs the same for its visited set plus a queue.

Common Pitfalls

  • Writing par[a] = b instead of par[find(a)] = find(b). Linking the vertices rather than their representatives silently splits components.
  • Recursive find on 2*10^5 vertices. A degenerate chain overflows the stack before compression has a chance to flatten it; the iterative loop here avoids that.
  • Returning early inside the edge loop. All edges must be processed before any query, since a later edge can connect the two.
  • Handling source == destination as a special case. It falls out: a vertex is always its own representative.
  • Assuming the graph is connected, or that edges are sorted. Neither is promised.

Full Solution — all languages

class Solution:
    def validPath(self, n, edges):
        par = list(range(n))
        def find(x):
            while par[x] != x:
                par[x] = par[par[x]]; x = par[x]
            return x
        for a, b in edges:
            par[find(a)] = find(b)
        return find(0) == find(n - 1)
SensAI
Beta
Tap the mic to stop voice mode