Browse curriculum

Breadth-First Search

The Breadth-First Search Pattern

Explore level by level using a queue: all nodes at distance 1, then all at distance 2, and so on. Because levels are visited in order, the first time a node is reached is guaranteed to be by a shortest path.

11

Interactive problems

3

Free to open

Recognise

How do you recognise a breadth-first search problem?

The question asks for the shortest path or minimum number of steps in an unweighted graph or grid, or for something computed per level ("level order traversal", "rightmost node of each row"). "Minimum number of moves" almost always means BFS.

Complexity

What is the time complexity of the breadth-first search pattern?

O(V + E) time, O(V) space for the queue and visited set. On a grid that is O(rows × cols).

Problems

Breadth-First Search practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Breadth-First Search problems by difficulty and complexity

The difficulty, running time and extra space of every breadth-first search solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Introduction to BFSEasyΩ(n)Θ(n)O(n)O(n)
BFS OverviewEasyΩ(1)Θ(n)O(n)O(n)
Binary Tree Level Order SumMediumΩ(n)Θ(n)O(n)O(n)
Binary Tree Rightmost NodeMediumΩ(n)Θ(n)O(n)O(n)
Binary Tree Zigzag Level Order TraversalMediumΩ(n)Θ(n)O(n)O(n)
Maximum Width of Binary TreeMediumΩ(n)Θ(n)O(n)O(n)
Graphs OverviewEasyΩ(1)Θ(V + E)O(V + E)O(V + E)
Minimum Knight MovesMediumΩ(1)Θ(max(|x|, |y|)²)O(max(|x|, |y|)²)O(max(|x|, |y|)²)
Rotting OrangesMediumΩ(R × C)Θ(R × C)O(R × C)O(R × C)
01 MatrixMediumΩ(R × C)Θ(R × C)O(R × C)O(R × C)
Bus RoutesHardΩ(1)Θ(S)O(S)O(S)
Curriculum

The underlying technique is covered from first principles in the breadth-first search lesson in the DSA visualizer curriculum. Breadth-First Search is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern