Neural Mastery
← Practice
Find if Path Exists in Grapheasy

Find if Path Exists in Graph

easy Coding Interview Patterns 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Graph & Tree Traversal, Step by Step
Structure
Algorithm
ABCDE
visiting A -> visited order so far: [A]
queue now: [B, C]
Step 1 / 5
Both modes run the real algorithm from the linked practice problem, one step at a time -- edit the graph or pick different tree nodes and every step recomputes live.

Determine graph reachability between two vertices using BFS or DFS traversal.

Related Skills

Task

Implement valid_path_exists(n, edges, source, destination): construct an adjacency list and use BFS with a visited set to determine if destination is reachable from source.

Function Signature

valid_path_exists(n: int, edges: list[list[int]], source: int, destination: int) -> bool

Examples

Example 1: Triangle Path Exists
Input: n = 3 edges = [[0, 1], [1, 2], [2, 0]] source = 0 destination = 2
Output: True
Example 2: Two Disconnected Components
Input: n = 6 edges = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]] source = 0 destination = 5
Output: False

Constraints

  • 1 <= n <= 2 * 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= source, destination < n
Python3Saved ✓
def valid_path_exists(n: int, edges: list[list[int]], source: int, destination: int) -> bool:
"""n: number of vertices (0 to n-1).
edges: list of undirected edges [u, v].
source, destination: start and goal vertices.
Return True if there is a valid path from source to destination, False otherwise."""
# Your implementation here
pass

Case 1: Triangle Path Exists
Input: n = 3 edges = [[0, 1], [1, 2], [2, 0]] source = 0 destination = 2
Expected: True
Case 2: Two Disconnected Components
Input: n = 6 edges = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]] source = 0 destination = 5
Expected: False