Skip to the solution
EasyDSAAsked in 20246 min read

Graph bfs traversal

1.3k views

The problem

Problem, as an interviewer would state it: "Implement a Breadth-First Search (bfs(graph, start)) over a graph represented as an adjacency list — visiting nodes level by level from start, and returning the order they were visited in."

Examples:

Code
bfs({A:["B","C"], B:["A","D"], C:["A","D"], D:["B","C"]}, "A");
// ["A", "B", "C", "D"]

Clarifying questions expected:

  • Is the graph represented as an adjacency list (an object/map of node → array of neighbors), and is it undirected (edges implied both ways) or directed?
  • If the graph is genuinely DISCONNECTED, should the traversal only visit start's own connected component, or attempt to visit every node in the whole graph regardless of reachability?
  • Does the graph need to be correctly handled if it contains a real CYCLE, without infinite-looping?

Code / implementation expected: Yes — real, direct proof of level-by-level visit order, correct behavior on a real disconnected graph, and correct termination on a real graph containing a cycle.

  • 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

6 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: BFS visits nodes level by level, correctly limits itself to the start node's own connected component, and correctly terminates on a real cyclic graph

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 16 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 nextEasy

Polyfill Array.prototype.map from scratch

Continue