Skip to the solution
HardDSAAsked in 20247 min read

Graph dfs traversal

520 views

The problem

Problem, as an interviewer would state it: "Implement a depth-first search over a graph given as an adjacency list, returning the order in which nodes are visited. Discuss edge cases, runtime, recursive versus iterative, and alternatives."

Examples:

Code
graph = { A: ["B", "C"], B: ["D"], C: ["D", "E"], D: ["F"], E: ["F"], F: [] }
dfs(graph, "A"); // ["A", "B", "D", "F", "C", "E"]

Clarifying questions expected:

  • Directed or undirected, and may it contain cycles, self loops or repeated edges?
  • Is the graph connected, or must every component be covered?
  • Which order do you want: pre-order (visit on entry), post-order (visit on exit)?

Code / implementation expected: Yes — real, direct proof that recursive and iterative versions agree, and of the subtle iterative variant that does not.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: iterative DFS reproduces the recursive order on random graphs, marking on push does not, and recursion overflows where the iterative version does not

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 151 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Build a Minimal State Machine Runner (States, Transitions, Guards)

Continue