All Paths from Source Lead to Destination - Problem

Given the edges of a directed graph where edges[i] = [ai, bi] indicates there is an edge between nodes ai and bi, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually end at destination.

This means:

  • At least one path exists from the source node to the destination node
  • If a path exists from the source node to a node with no outgoing edges, then that node is equal to destination
  • The number of possible paths from source to destination is a finite number

Return true if and only if all roads from source lead to destination.

Input & Output

Example 1 — Valid Path Structure
$ Input: edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
Output: true
💡 Note: There are two paths from source 0 to destination 3: 0→1→3 and 0→2→3. Both paths end at destination 3, and there are no cycles, so return true.
Example 2 — Wrong Destination
$ Input: edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 2
Output: false
💡 Note: Path 0→1→3 ends at node 3, not at the specified destination 2. Since not all paths lead to destination, return false.
Example 3 — Cycle Present
$ Input: edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2
Output: false
💡 Note: There is a self-loop at node 1 (1→1), creating an infinite cycle. This violates the finite paths requirement, so return false.

Constraints

  • 1 ≤ edges.length ≤ 104
  • edges[i].length == 2
  • 0 ≤ ai, bi ≤ 103
  • 0 ≤ source ≤ 103
  • 0 ≤ destination ≤ 103

Visualization

Tap to expand
All Paths from Source Lead to DestinationInput Graph0Source123DestinationPath AnalysisPath 1: 0 → 1 → 3Path 2: 0 → 2 → 3Both end at destination ✓Validation Checks:✓ All paths end at destination (3)✓ No cycles detected✓ Finite number of pathsResult: TRUE
Understanding the Visualization
1
Input Graph
Directed graph with edges, source node, and destination node
2
Path Validation
Check all possible paths using DFS with cycle detection
3
Result
True if all paths end at destination with no infinite loops
Key Takeaway
🎯 Key Insight: Use three-state DFS (WHITE/GRAY/BLACK) to detect cycles while ensuring all leaf nodes equal the destination
Asked in
Google 15 Facebook 12 Microsoft 8
35.0K Views
Medium Frequency
~25 min Avg. Time
892 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