FastPrepAll Simple Paths in an Undirected Graph

All Simple Paths in an Undirected Graph

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Build an undirected graph with nodes 0..n-1 from edges. Return every simple path from source to target.

A simple path repeats no node. Sort each adjacency list and return paths in depth-first lexicographic order.

Function

allSimplePaths(n: int, edges: int[][], source: int, target: int) → int[][]

Examples

Example 1

n = 4edges = [[0,1],[1,3],[0,2],[2,3],[1,2]]source = 0target = 3return = [[0,1,2,3],[0,1,3],[0,2,1,3],[0,2,3]]

DFS follows sorted neighbors and never repeats a node.

Constraints

  • 1 <= n <= 15.
  • Edges are unique undirected pairs.
  • Source and target are valid distinct nodes.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int[][] allSimplePaths(int n, int[][] edges, int source, int target) {
  // Write your code here.
}
n4
edges[[0,1],[1,3],[0,2],[2,3],[1,2]]
source0
target3
expected[[0,1,2,3],[0,1,3],[0,2,1,3],[0,2,3]]
Checking account…