SDE & MLE Prep

1971. Find if Path Exists in Graph

Problem

Decide whether there is a path from source to destination in an undirected graph with nodes 0…n − 1 and the given edges.

Example: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 → true

Constraints: up to 2·10⁵ nodes and edges.

Union every edge, then check whether source and destination share a root (or BFS from the source).

Complexity: O(E · α(V)).

class Solution:
    def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
        parent = list(range(n))

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        for a, b in edges:
            parent[find(a)] = find(b)
        return find(source) == find(destination)