Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Every route from source to target

Medium · Target 20 minutes · Graphs · Type asked atAmazonMetaBloomberg

A directed graph has n nodes numbered 0 to n − 1 and a list of edges, each [u, v] an edge from u to v. Return every path from node 0 to node n − 1 that does not repeat a node, as lists of nodes. Order the paths lexicographically: compare them element by element, and a path that is a prefix of another comes first.

Examples

InputOutputWhy
n = 4, edges = [[0,1],[0,2],[1,3],[2,3]][[0,1,3],[0,2,3]]Two routes.
n = 4, edges = [[0,1],[1,2],[2,0],[2,3]][[0,1,2,3]]The cycle back to 0 is never taken: 0 is already on the path.
n = 3, edges = [[0,1]][]Node 2 cannot be reached.

Constraints

  • 2 ≤ n ≤ 12
  • 0 ≤ edges.length ≤ n(n − 1)
  • No self-loops or repeated edges

Hints

Hint 1

Search depth-first from 0, keeping the current path in a list.

Hint 2

When the search reaches n − 1, copy the path into the answer.

Hint 3

A node is unavailable only while it is on the current path: remove it when the search backs out. Sorting each adjacency list makes the answer come out in lexicographic order.

Where people lose marks

  • Marking nodes visited for good, as in a plain traversal: paths that share a node are then lost.
  • Appending the path list itself rather than a copy, so every recorded path changes as the search continues.
  • Not guarding against cycles when the graph is not guaranteed to be acyclic.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.