TRT
Sign in
easyAdvancedLeetCode#adjacency lists#reachability

Find if path exists in graph

Build adjacency lists from an edge list and decide whether two vertices are connected with BFS or DFS.

The Runtime Theory Team1 min read
Taught inRepresenting graphsPro — members onlyA graph is a set of vertices joined by edges. How you store it, as adjacency lists, an adjacency matrix or an edge list, decides the cost of every algorithm you run on it.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 3, edges = [[0, 1], [1, 2], [2, 0]], source = 0, destination = 2

outtrue

inn = 6, edges = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]], source = 0, destination = 5

outfalse

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

  1. adj = [[] for _ in range(n)]; for each edge, append both directions.
  2. Run BFS or DFS from source with a visited set; return true if you reach destination.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save