Pattern 12 of 22

Breadth-First Search Pattern: Template + 233 LeetCode Problems

Expand outward level by level, so the first time you arrive is the shortest way.

Easy
23
Medium
148
Hard
62
Time
O(V + E)

What the breadth-first search pattern is

Breadth-first search visits every node at distance k before any node at distance k+1, and that ordering is the entire reason to prefer it: on an unweighted graph the first time BFS reaches a node is guaranteed to be by a shortest path, so the search can stop the moment the target appears. Distance is tracked either by carrying it in the queue alongside the node, or by draining the queue one full level at a time — the level form is what you want when the answer is per-level, such as a right-side view or the maximum value on each row. Mark nodes as seen when they are enqueued, not when they are dequeued, or the same node enters the queue once per incoming edge and the cost stops being linear. The multi-source variant is worth recognising on sight: seeding the queue with every starting cell at once computes the distance from the nearest source for every cell in one pass, which is how rotting oranges and nearest-zero problems avoid running a separate BFS per source.

When to use it

  • The question is the minimum number of steps, moves, or transformations.
  • The graph is unweighted — with weights, this becomes Dijkstra and needs a heap.
  • The answer is per level: a level order, a right-side view, a level sum.
  • Distance from the nearest of several sources is needed, which one multi-source pass gives you.

The breadth-first search template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 233 problems listed below.

PythonBreadth-First Search template
from collections import deque

def shortest_steps(graph, start, goal):
    seen = {start}
    queue = deque([(start, 0)])

    while queue:
        node, steps = queue.popleft()
        if node == goal:
            return steps               # first arrival is the shortest one
        for neighbour in graph[node]:
            if neighbour not in seen:
                seen.add(neighbour)    # mark on ENQUEUE or the queue duplicates
                queue.append((neighbour, steps + 1))

    return -1

Complexity characteristics

Time
O(V + E)
Auxiliary space
O(V)

The same linear traversal cost as depth-first search: the difference is the order of the visits, not the amount of work. The queue holds the widest level rather than the deepest path, which on a wide graph or a filled grid is O(V) and can be considerably more memory than DFS uses on the same input. A multi-source pass costs the same single traversal however many sources are seeded, which is the whole reason to prefer it to one BFS per source.

Eyes only

Meet the breadth-first search problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 233 breadth-first search LeetCode problems

Every problem in the library the breadth-first search pattern applies to, grouped by LeetCode's own difficulty rating. 185 of the 233 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (23)

Easy problems
No.Problem
0100Same Tree
0101Symmetric Tree
0104Maximum Depth of Binary Tree
0111Minimum Depth of Binary Tree
0112Path Sum
0226Invert Binary Tree
0404Sum of Left Leaves
0463Island Perimeter
0530Minimum Absolute Difference in BST
0559Maximum Depth of N-ary Tree
0617Merge Two Binary Trees
0637Average of Levels in Binary Tree
0653Two Sum IV - Input is a BST
0733Flood Fill
0933Number of Recent Calls
0346Moving Average from Data StreamPremium
0783Minimum Distance Between BST Nodes
0965Univalued Binary Tree
0993Cousins in Binary Tree
1379Find a Corresponding Node of a Binary Tree in a Clone of That Tree
1469Find All The Lonely NodesPremium
1971Find if Path Exists in Graph
2073Time Needed to Buy Tickets

Medium (148)

Medium problems
No.Problem
0102Binary Tree Level Order Traversal
0103Binary Tree Zigzag Level Order Traversal
0107Binary Tree Level Order Traversal II
0116Populating Next Right Pointers in Each Node
0117Populating Next Right Pointers in Each Node II
0130Surrounded Regions
0133Clone Graph
0199Binary Tree Right Side View
0200Number of Islands
0207Course Schedule
0210Course Schedule II
0279Perfect Squares
0310Minimum Height Trees
0322Coin Change
0365Water and Jug Problem
0399Evaluate Division
0417Pacific Atlantic Water Flow
0429N-ary Tree Level Order Traversal
0433Minimum Genetic Mutation
0449Serialize and Deserialize BST
0513Find Bottom Left Tree Value
0515Find Largest Value in Each Tree Row
0529Minesweeper
054201 Matrix
0547Number of Provinces
0622Design Circular Queue
0623Add One Row to Tree
0641Design Circular Deque
0655Print Binary Tree
0662Maximum Width of Binary Tree
0672Bulb Switcher II
0684Redundant Connection
0690Employee Importance
0695Max Area of Island
0721Accounts Merge
0743Network Delay Time
0787Cheapest Flights Within K Stops
0841Keys and Rooms
0909Snakes and Ladders
0994Rotting Oranges
1161Maximum Level Sum of a Binary Tree
1448Count Good Nodes in Binary Tree
1466Reorder Routes to Make All Paths Lead to the City Zero
1926Nearest Exit from Entrance in Maze
0261Graph Valid TreePremium
0281Zigzag IteratorPremium
0286Walls and GatesPremium
0314Binary Tree Vertical Order TraversalPremium
0323Number of Connected Components in an Undirected GraphPremium
0339Nested List Weight SumPremium
0364Nested List Weight Sum IIPremium
0490The MazePremium
0505The Maze IIPremium
0582Kill ProcessPremium
0694Number of Distinct IslandsPremium
0737Sentence Similarity IIPremium
0742Closest Leaf in a Binary TreePremium
0752Open the Lock
0785Is Graph Bipartite?
0797All Paths From Source to Target
0802Find Eventual Safe States
0863All Nodes Distance K in Binary Tree
0865Smallest Subtree with all the Deepest Nodes
0886Possible Bipartition
0919Complete Binary Tree Inserter
0934Shortest Bridge
0950Reveal Cards In Increasing Order
0958Check Completeness of a Binary Tree
0959Regions Cut By Slashes
0967Numbers With Same Consecutive Differences
1020Number of Enclaves
1034Coloring A Border
1042Flower Planting With No Adjacent
1087Brace ExpansionPremium
1091Shortest Path in Binary Matrix
1102Path With Maximum Minimum ValuePremium
1123Lowest Common Ancestor of Deepest Leaves
1129Shortest Path with Alternating Colors
1162As Far from Land as Possible
1197Minimum Knight MovesPremium
1202Smallest String With Swaps
1215Stepping NumbersPremium
1236Web CrawlerPremium
1242Web Crawler MultithreadedPremium
1245Tree DiameterPremium
1254Number of Closed Islands
1257Smallest Common RegionPremium
1261Find Elements in a Contaminated Binary Tree
1267Count Servers that Communicate
1273Delete Tree NodesPremium
1302Deepest Leaves Sum
1306Jump Game III
1311Get Watched Videos by Your Friends
1315Sum of Nodes with Even-Valued Grandparent
1319Number of Operations to Make Network Connected
1361Validate Binary Tree Nodes
1376Time Needed to Inform All Employees
1391Check if There is a Valid Path in a Grid
1430Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary TreePremium
1443Minimum Time to Collect All Apples in a Tree
1457Pseudo-Palindromic Paths in a Binary Tree
1462Course Schedule IV
1485Clone Binary Tree With Random PointerPremium
1490Clone N-ary TreePremium
1519Number of Nodes in the Sub-Tree With the Same Label
1559Detect Cycles in 2D Grid
1602Find Nearest Right Node in Binary TreePremium
1609Even Odd Tree
1625Lexicographically Smallest String After Applying Operations
1631Path With Minimum Effort
1654Minimum Jumps to Reach Home
1660Correct a Binary TreePremium
1670Design Front Middle Back Queue
1730Shortest Path to Get FoodPremium
1740Find Distance in a Binary TreePremium
1765Map of Highest Peak
1778Shortest Path in a Hidden GridPremium
1810Minimum Path Cost in a Hidden GridPremium
1823Find the Winner of the Circular Game
1905Count Sub Islands
1992Find All Groups of Farmland
1993Operations on Tree
2039The Time When the Network Becomes Idle
2059Minimum Operations to Convert Number
2101Detonate the Maximum Bombs
2146K Highest Ranked Items Within a Price Range
2174Remove All Ones With Row and Column Flips IIPremium
2192All Ancestors of a Node in a Directed Acyclic Graph
2316Count Unreachable Pairs of Nodes in an Undirected Graph
2368Reachable Nodes With Restrictions
2385Amount of Time for Binary Tree to Be Infected
2415Reverse Odd Levels of Binary Tree
2445Number of Nodes With Value OnePremium
2467Most Profitable Path in a Tree
2471Minimum Number of Operations to Sort a Binary Tree by Level
2477Minimum Fuel Cost to Report to the Capital
2492Minimum Score of a Path Between Two Cities
2556Disconnect Path in a Binary Matrix by at Most One Flip
2583Kth Largest Sum in a Binary Tree
2596Check Knight Tour Configuration
2641Cousins in Binary Tree II
2658Maximum Number of Fish in a Grid
2685Count the Number of Complete Components
2773Height of Special Binary TreePremium
2812Find the Safest Path in a Grid
2850Minimum Moves to Spread Stones Over Grid
2852Sum of Remoteness of All CellsPremium
2998Minimum Number of Operations to Make X and Y Equal

Hard (62)

Hard problems
No.Problem
0126Word Ladder II
0127Word Ladder
0297Serialize and Deserialize Binary Tree
0301Remove Invalid Parentheses
0329Longest Increasing Path in a Matrix
0407Trapping Rain Water II
0488Zuma Game
0514Freedom Trail
0675Cut Off Trees for Golf Event
0685Redundant Connection II
0749Contain Virus
0778Swim in Rising Water
0269Alien DictionaryPremium
0302Smallest Rectangle Enclosing Black PixelsPremium
0317Shortest Distance from All BuildingsPremium
0428Serialize and Deserialize N-ary TreePremium
0431Encode N-ary Tree to Binary TreePremium
0499The Maze IIIPremium
0711Number of Distinct Islands IIPremium
0765Couples Holding Hands
0773Sliding Puzzle
0815Bus Routes
0827Making A Large Island
0839Similar String Groups
0847Shortest Path Visiting All Nodes
0854K-Similar Strings
0864Shortest Path to Get All Keys
0924Minimize Malware Spread
0928Minimize Malware Spread II
0987Vertical Order Traversal of a Binary Tree
1036Escape a Large Maze
1096Brace Expansion II
1203Sort Items by Groups Respecting Dependencies
1210Minimum Moves to Reach Target with Rotations
1263Minimum Moves to Move a Box to Their Target Location
1284Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
1293Shortest Path in a Grid with Obstacles Elimination
1298Maximum Candies You Can Get from Boxes
1345Jump Game IV
1368Minimum Cost to Make at Least One Valid Path in a Grid
1377Frog Position After T Seconds
1483Kth Ancestor of a Tree Node
1568Minimum Number of Days to Disconnect Island
1970Last Day Where You Can Still Cross
2045Second Minimum Time to Reach Destination
2092Find All People With Secret
2204Distance to a Cycle in Undirected GraphPremium
2258Escape the Spreading Fire
2277Closest Node to Path in TreePremium
2290Minimum Obstacle Removal to Reach Corner
2328Number of Increasing Paths in a Grid
2360Longest Cycle in a Graph
2458Height of Binary Tree After Subtree Removal Queries
2493Divide Nodes Into the Maximum Number of Groups
2503Maximum Number of Points From Grid Queries
2534Time Taken to Cross the DoorPremium
2577Minimum Time to Visit a Cell In a Grid
2608Shortest Cycle in a Graph
2612Minimum Reverse Operations
2617Minimum Number of Visited Cells in a Grid
2814Minimum Time Takes to Reach Destination Without DrowningPremium
2858Minimum Edge Reversals So Every Node Is Reachable

Breadth-First Search pattern FAQ

What is the breadth-first search pattern?

Breadth-first search visits every node at distance k before any node at distance k+1, and that ordering is the entire reason to prefer it: on an unweighted graph the first time BFS reaches a node is guaranteed to be by a shortest path, so the search can stop the moment the target appears.

How many LeetCode problems use the breadth-first search pattern?

This page lists 233 LeetCode problems that the breadth-first search pattern applies to: 23 Easy, 148 Medium and 62 Hard. 185 of them carry a complete Python solution with complexity analysis.

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

O(V + E) time and O(V) space. The same linear traversal cost as depth-first search: the difference is the order of the visits, not the amount of work. The queue holds the widest level rather than the deepest path, which on a wide graph or a filled grid is O(V) and can be considerably more memory than DFS uses on the same input. A multi-source pass costs the same single traversal however many sources are seeded, which is the whole reason to prefer it to one BFS per source.

When should I use the breadth-first search pattern in an interview?

The question is the minimum number of steps, moves, or transformations. The graph is unweighted — with weights, this becomes Dijkstra and needs a heap.

Which breadth-first search problem should I start with?

LeetCode 100. Same Tree is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to breadth-first search?

Depth-First Search, Matrix and Grid, Topological Sort, Heap / Priority Queue. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.