Find if Path Exists in Graph

EasyGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An undirected graph has n vertices labelled 0 to n - 1. Its edges are given as edges[i] = [u, v], meaning u and v are connected. There are no self-loops and no duplicate edges. Given a source and a destination vertex, return true if you can travel from source to destination along the edges, and false otherwise. A vertex can always reach itself.

Examples

Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Go 0 -> 2 directly, or 0 -> 1 -> 2.
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
Vertices {0,1,2} and {3,4,5} form separate components.

Constraints

  • 1 <= n <= 2 * 10^5
  • 0 <= edges.length <= 2 * 10^5
  • 0 <= u, v <= n - 1 and u != v
  • 0 <= source, destination <= n - 1
  • There are no duplicate edges

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems