Graph Path Finder - Problem

Given an undirected graph represented as an adjacency list and two nodes start and end, find all possible paths between them.

Return a list containing:

  • All paths from start to end (as arrays of node values)
  • The shortest path (fewest nodes)
  • The longest path (most nodes)

Note: If multiple paths have the same length, return any one of them for shortest/longest.

Input & Output

Example 1 — Simple Path
$ Input: graph = {"1":[2,3], "2":[1,4], "3":[1,4], "4":[2,3]}, start = 1, end = 4
Output: [[[1,2,4],[1,3,4]], [1,2,4], [1,2,4]]
💡 Note: Two paths exist from node 1 to 4: [1,2,4] and [1,3,4]. Both have length 3, so either can be shortest/longest.
Example 2 — Multiple Lengths
$ Input: graph = {"1":[2], "2":[1,3,4], "3":[2,4], "4":[2,3]}, start = 1, end = 4
Output: [[[1,2,4],[1,2,3,4]], [1,2,4], [1,2,3,4]]
💡 Note: Path [1,2,4] has length 3, path [1,2,3,4] has length 4. Shortest is [1,2,4], longest is [1,2,3,4].
Example 3 — Same Start and End
$ Input: graph = {"1":[2], "2":[1]}, start = 1, end = 1
Output: [[[1]], [1], [1]]
💡 Note: When start equals end, return single-node path [1] for all three results.

Constraints

  • 1 ≤ number of nodes ≤ 20
  • Graph is undirected
  • Node values are positive integers
  • Graph may be disconnected

Visualization

Tap to expand
INPUT GRAPHDFS ALGORITHMRESULT PATHS1234StartEndAdjacency List:1: [2, 3]2: [1, 4]3: [1, 4]4: [2, 3]Find paths: 1 → 41234Step 1: Start DFS at node 1Step 2: Explore neighbors 2,3Step 3: From 2, reach 4 → path [1,2,4]Step 4: Backtrack, try 3 → 4Step 5: Found path [1,3,4]Step 6: Compare path lengthsAll Paths Found:Path 1: [1, 2, 4] (length: 3)Path 2: [1, 3, 4] (length: 3)Total paths: 2Shortest Path:[1, 2, 4] (3 nodes)Same as longestLongest Path:[1, 3, 4] (3 nodes)Equal length pathsKey Insight:DFS with backtracking systematically explores all paths while tracking visited nodes to avoid cycles.TutorialsPoint - Graph Path Finder | DFS with Backtracking
Asked in
Google 25 Amazon 18 Facebook 15 Microsoft 12
28.5K 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