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

Depth-first order of a graph

Easy · Target 12 minutes · Graphs

A graph has n nodes numbered 0 to n − 1 and a list of undirected edges, each a pair [u, v]. Traverse it depth-first under these rules, and return the nodes in the order they are first visited:

  • Start at node 0.
  • From a node, move to its smallest-numbered unvisited neighbour, and continue from there.
  • When a node has no unvisited neighbour, go back to the node you came from and continue from it.
  • When the search returns to its start with nothing left, begin again at the smallest-numbered node not yet visited, until every node has been visited.

Examples

InputOutputWhy
n = 7, edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[5,6]][0, 1, 3, 2, 4, 5, 6]From 3 the search tries 2 before 4. Nodes 5 and 6 are a separate part, reached by restarting.
n = 3, edges = [][0, 1, 2]No edges: every node is its own start.
n = 4, edges = [[0,3],[3,2],[2,1]][0, 3, 2, 1]A path walked from one end.

Constraints

  • 1 ≤ n ≤ 200
  • 0 ≤ edges.length ≤ n(n − 1)/2
  • No self-loops and no repeated edges

Hints

Hint 1

Build an adjacency list first, and sort each node's neighbours so the smallest is tried first.

Hint 2

A recursive function dfs(u) marks u, records it, then calls itself on each unvisited neighbour in order.

Hint 3

Call dfs from every node, in increasing order, that is still unvisited after the previous calls.

Where people lose marks

  • Adding each undirected edge in one direction only, so some neighbours are never seen.
  • Forgetting the outer loop: on a disconnected graph only the first part is visited.
  • Marking a node visited when the search leaves it rather than when it enters, so a cycle visits it twice.
  • An iterative version that pushes all neighbours at once visits them in a different order from the recursive one; to match it, push them in reverse or keep a neighbour index per node.
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.