Find if Path Exists in Graph - Problem

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

You want to determine if there is a valid path that exists from vertex source to vertex destination.

Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.

Input & Output

Example 1 — Basic Connected Graph
$ Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
💡 Note: There are two paths from vertex 0 to vertex 2: 0→1→2 and 0→2. Both are valid paths.
Example 2 — Disconnected Components
$ Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
💡 Note: Vertex 0 is in component {0,1,2} while vertex 5 is in component {3,4,5}. No path exists between them.
Example 3 — Same Source and Destination
$ Input: n = 1, edges = [], source = 0, destination = 0
Output: true
💡 Note: Source and destination are the same vertex. A path always exists from a vertex to itself.

Constraints

  • 1 ≤ n ≤ 2 × 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi ≤ n - 1
  • ui != vi
  • 0 ≤ source, destination ≤ n - 1

Visualization

Tap to expand
Find if Path Exists in Graph INPUT 0 1 2 SOURCE DEST n = 3 edges = [[0,1],[1,2],[2,0]] source = 0 destination = 2 Bi-directional graph ALGORITHM STEPS 1 Build Adjacency List 0: [1,2], 1: [0,2], 2: [1,0] 2 Start DFS from source Push node 0 to stack 3 Explore neighbors Mark visited, check dest 4 Found destination! Return true DFS Traversal: Visit 0 (source) Visit 1 (neighbor of 0) Visit 2 (neighbor of 1) 2 == destination: OK FINAL RESULT 0 1 2 Path: 0 --> 1 --> 2 Output: true Valid path exists from source 0 to dest 2 Key Insight: DFS explores as deep as possible along each branch before backtracking. For path existence, we simply need to find if destination is reachable from source. Use a visited set to avoid cycles. Time: O(V + E) | Space: O(V) for visited array and recursion stack. TutorialsPoint - Find if Path Exists in Graph | Depth-First Search (DFS)
Asked in
Facebook 15 Amazon 12 Google 10 Microsoft 8
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen