Given n vertices, a list of undirected edges and two vertices, return whether there is a path between them.
Before you code
The input is an edge list, which is slow to query. Convert it into adjacency lists first, then any search from the source answers the question.
Hints
adj = [[] for _ in range(n)]; for each edge, append both directions.- Run BFS or DFS from
sourcewith a visited set; return true if you reachdestination. - Union-find, in the advanced level, answers the same question without building lists.
Production & complexity notes
When solving Find if path exists in graph on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Representing graphs to reinforce the underlying pattern.
What it practices
Turning an edge list into adjacency lists, from Representing graphs.