Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Breadth-First Traversal Order

Graphseasy

Given an adjacency list `adj` (where `adj[i]` lists neighbors of node `i`) and a `start` node, implement `bfs(adj, start)` returning the order nodes are visited by breadth-first search. Visit neighbors in listed order.

Sample tests

Input: bfs([[1,2],[0,3],[0,3],[1,2]], 0)
Output: [0,1,2,3]
Input: bfs([[1],[0]], 1)
Output: [1,0]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Marking visited on dequeue instead of enqueue can revisit nodes.

Learning resources

  • Wikipedia: Graph traversal
Approach & explanation (try first)

BFS explores level by level with a queue. O(V + E) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.