v9.1.1
Menu

Find if Path Exists in Graph

easyPROGraphs & BFS/DFSLinkedIn DSA

Given n nodes labelled 0 to n - 1, a list of undirected edges, and two nodes source and destination, return True if a path exists between them, otherwise False.

Implement valid_path(n, edges, source, destination), where edges is a list of [u, v] pairs. In the example below, the input is shown as: first line = n, second = edges as u:v comma-separated (or 'none'), third = source destination.

Example

Input
3
0:1,1:2,2:0
0 2
Output
True
Reasoning
  • Input: n=3n = 3 nodes labelled 0,1,20, 1, 2; three undirected edges {0,1}\{0,1\}, {1,2}\{1,2\}, {2,0}\{2,0\} (each can be walked in either direction); source =0= 0 and destination =2= 2.
  • The question is purely about reachability: is there some sequence of edges starting at node 0 and ending at node 2? Length and cost don't matter.
  • Starting from node 0, its neighbours are {1,2}\{1, 2\}. Node 2 is already among them, so the one-edge path 0→20 \to 2 exists. The two-edge route 0→1→20 \to 1 \to 2 works too.
  • In fact all three nodes form one connected component (a triangle), so every pair of nodes here is reachable from each other.
  • Output: True, a boolean, because 0 and 2 lie in the same component.
  • Notice the answer is False exactly when the two nodes sit in different components, e.g. a graph split into {0,1,2}\{0,1,2\} and {3,4,5}\{3,4,5\} with source =0= 0, destination =5= 5. And when source equals destination, the empty path counts, so the answer is True.

Constraints

  • 1 <= n <= 2 * 10^5
  • 0 <= edges.length <= 2 * 10^5

Learn this in

More from LinkedIn DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.