Browse curriculum

Breadth-First Search

Breadth-First Search Interview Questions: 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. Below are the breadth-first search interview questions from LeetCode, each with a step-by-step visual solution.

18

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 interview questions: 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)
Maximum Level Sum of a Binary TreeMediumΩ(n)Θ(n)O(n)O(n)
Binary Tree Level Order TraversalMediumΩ(n)Θ(n)O(n)O(w)
Symmetric TreeEasyΩ(1)Θ(n)O(n)O(w)
Binary Tree Right Side ViewMediumΩ(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)
All Nodes Distance K in 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)
Nearest Exit from Entrance in MazeMediumΩ(1)Θ(m · n)O(m · n)O(m · n)
Walls and GatesMediumΩ(m · n)Θ(m · n)O(m · n)O(m · n)
01 MatrixMediumΩ(R × C)Θ(R × C)O(R × C)O(R × C)
Bus RoutesHardΩ(1)Θ(S)O(S)O(S)
Word LadderHardΩ(1)Θ(N · L · 26)O(N · L · 26)O(N · L)
Cheapest Flights Within K StopsMediumΩ(k · E)Θ(k · E)O(k · E)O(n)
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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern