Browse Curriculum

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

How to 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.

Time and space complexity

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

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++.


Related patterns and concepts

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 16 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.