Skip to content

Pattern · Interview prep

Breadth-First Search

Visit nodes in the order they were discovered, one layer at a time. When every edge costs the same, the first time you reach a target is the fewest steps.

What it is

What is the breadth-first search pattern?

Breadth-first search keeps a frontier of nodes that sit at the same distance from the start. You finish that frontier, and the nodes you discover along the way become the next one. A queue is the frontier: new neighbors join the back, and the next node to handle comes from the front.

  • Level order. The root is the first frontier. Its children are the next. Enqueue the left child before the right child so each level stays left to right.
  • Fewest equal-cost steps. Every edge costs one. The layer on which the queue first reaches the target is the distance. A later path to the same node cannot be shorter.
  • What is ready now. The frontier can be every course whose prerequisites are done. If something never becomes ready, the rules contain a cycle.
Root 1, left child 2, right child 3
level2, 3

2 and 3 were discovered together

WindowLLeft endRRight end
A tree with visit numbers 1 to 7 and one band per level. Breadth-first visits 1 root, then 2 and 3 the two children, then 4, 5 and 6 the next level left to right, and last 7 the deepest node.
Each level is finished before the next level starts.

When to use it

How do you recognize a breadth-first search problem?

Read the statement for these signals before you dive down one branch.

Read the full recognition guide: DFS vs BFS: how to tell which one a problem needs

Phrases to watch for

  • level order
  • shortest path
  • minimum steps
  • fewest edges
  • unweighted
  • nearest
  • frontier
  1. 1

    The answer is grouped by distance

    A level, a ring of cells, or a ladder of a given length is one frontier. Finish it before the nodes you just found.

  2. 2

    Every step costs the same

    One letter, one edge, or one grid step. The first visit is then the shortest, so you can stop when you reach the target.

  3. 3

    Order of discovery is the order of service

    The oldest waiting node is next. A stack would hand back the neighbor you just found and reverse the layer.

Looks similar, but isn’t

  • You need one branch to finish first

    A swap of a subtree, a path through both children, or a cycle on the open path is depth-first. Grouping by level afterward is extra work a queue does for you.

  • Edges have different costs

    The first time you arrive is no longer the cheapest. Take the cheapest known step next, which is a heap, not a plain queue.

  • You can discard half of a sorted row

    Binary search jumps to the middle. Breadth-first still walks neighbors when the question is about distance, not a lookup.

Worked example

How does one level finish before the next?

Start the frontier at the root. Record every node in it, then build the next frontier from their children, left then right. On a tree whose root is 1, with 2 on the left and 3 on the right, the levels are [[1], [2, 3]]. The same grouping is the tree problem you can practice below.

TypeScriptvaluesByLevel
type Node = { value: number; left: Node | null; right: Node | null }; function valuesByLevel(root: Node | null): number[][] {  if (root === null) return [];  const levels: number[][] = [];  let frontier: Node[] = [root];   while (frontier.length > 0) {    const values: number[] = [];    const next: Node[] = [];    for (const node of frontier) {      values.push(node.value);      if (node.left !== null) next.push(node.left);      if (node.right !== null) next.push(node.right);    }    levels.push(values);    frontier = next;  }   return levels;}

Record this frontier, then let its children become the next one.

Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.

Complexity

  • TimeO(n)

    Each node enters the frontier once and is recorded once.

  • SpaceO(n)

    The widest level can hold every node in that layer, and the output stores every value.

An empty tree

A null root has no frontier. Return an empty list of levels before you read a value.

The same frontier on a graph

Mark a node seen when you enqueue it, not when you dequeue it. Otherwise two neighbors can place the same node on the frontier twice.

Step by step on root 1, left 2, right 3

  1. 1

    The frontier starts as the root. Record 1. Its children, 2 and then 3, become the next frontier.

  2. 2

    The frontier is now 2, then 3. Record both. Neither has a child, so the next frontier is empty.

  3. 3

    The walk stops. The levels are [[1], [2, 3]].

Common mistakes

What mistakes do people make with breadth-first search?

  • Letting the next level join the current count

    If you enqueue children into the same queue and then keep taking until it is empty, the row never ends. Later levels mix into the one you are recording.

    InsteadSnapshot the frontier, or count how many nodes are waiting, before you enqueue anyone new. Only that many nodes belong to this level.

  • Enqueueing the right child first

    The level is the order of discovery. Right-then-left writes the row backwards.

    InsteadEnqueue the left child, then the right child. On a grid, use a fixed neighbor order and keep it.

  • Marking a node seen when you dequeue it

    Several neighbors can enqueue the same unseen node. You then walk it more than once, and a shortest-path count inflates.

    InsteadMark the node seen at the moment you discover it, before it joins the queue.

  • Using the first visit when steps have different costs

    A cheap long route can arrive after an expensive short one. Stopping at the first visit returns the wrong distance.

    InsteadUse a plain queue only when every edge costs the same. When costs differ, always expand the cheapest unfinished step.

Practice it in Algofily

Which Algofily problems train breadth-first search?

4 problems are tagged Breadth-First Search. Level by Level is in Algofily 40. The others count islands, check whether courses can finish, and find the shortest word ladder.

A lock means the problem opens after you create an account. Pair With Target is open to try without one.

The same tree drawn twice with visit numbers. Depth-first preorder visits 1 root, 2 left child, 3 its child, 4 that node's child, 5 the left child's other child, 6 the right child, 7 its child. Breadth-first visits 1 root, 2 and 3 the two children, 4, 5 and 6 the next level left to right, then 7 the deepest node.
One tree, two visit orders: across a level, or down a branch.

Start Learning.

Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.