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

Breadth-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. Traverse it breadth-first and return the nodes in the order they are taken from the queue:

  • Start with node 0 in the queue.
  • Repeatedly take the node at the front. Add each of its unvisited neighbours to the back of the queue, in increasing order of number.
  • When the queue is empty and some node is unvisited, put the smallest-numbered such node in the queue and continue.

Examples

InputOutputWhy
n = 7, edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[5,6]][0, 1, 2, 3, 4, 5, 6]1 and 2 are one step from 0, 3 is two steps, 4 is three. Then the second part.
n = 5, edges = [[0,4],[4,3],[3,2],[2,1]][0, 4, 3, 2, 1]A path: one node per level.
n = 4, edges = [][0, 1, 2, 3]Four separate nodes.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ edges.length ≤ 2 · 10⁴
  • No self-loops and no repeated edges

Hints

Hint 1

Use a queue (a deque, or an array with a moving head index), not a list you remove from the front of.

Hint 2

Mark a node visited at the moment you add it to the queue. Then it can never be added twice.

Hint 3

Wrap the whole search in a loop over every node, starting a new search from each one still unvisited.

Where people lose marks

  • Using list.pop(0) in Python or array.shift() in JavaScript: each is O(n), and the traversal becomes quadratic.
  • Marking on dequeue, so the same node is queued many times on a dense graph.
  • Forgetting the outer loop, which leaves every other part of a disconnected graph unvisited.
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.