Pattern · 45 problems
BFS and DFS Interview Problems
Depth-first dives and backs out. Breadth-first spreads in rings. I pick by asking whether the first arrival must be the shortest.
Free: write the code and run it, no sign-up.
When I reach for it
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
- You count regions or connected pieces.
Problems, easiest first
7 easy · 29 medium · 9 hard. Open one to read it, then write it in the free editor.
- Same TreeeasyTrees
- Subtree of Another TreeeasyTreesStrings
- Maximum Depth of Binary TreeeasyTrees
- Invert Binary TreeeasyTrees
- Balanced Binary TreeeasyTrees
- Diameter of Binary TreeeasyTrees
- Flood FilleasyArrays & Hashing
- Clone GraphmediumGraphs
- Construct Binary Tree from Preorder and Inorder TraversalmediumTreesArrays & Hashing
- Kth Smallest Element in a BSTmediumTrees
- Lowest Common Ancestor of a Binary Search TreemediumTrees
- Number of Connected Components in an Undirected GraphmediumGraphs
- Word SearchmediumBacktrackingStrings
- Design Add and Search Words Data StructuremediumTreesDesign
- Binary Tree Level Order TraversalmediumTrees
- Coin ChangemediumDynamic ProgrammingArrays & Hashing
- Course SchedulemediumHeapsGraphs
- Graph Valid TreemediumGraphs
- Number of IslandsmediumGraphsArrays & Hashing
- Pacific Atlantic Water FlowmediumGraphsArrays & Hashing
- Validate Binary Search TreemediumTrees
- Binary Tree Right Side ViewmediumTrees
- Cheapest Flights Within K StopsmediumHeapsGraphs
- Count Good Nodes in Binary TreemediumTrees
- Course Schedule IImediumGraphs
Show the other 20 problems
- Max Area of IslandmediumGraphsArrays & Hashing
- Network Delay TimemediumHeapsGraphs
- Redundant ConnectionmediumGraphsArrays & Hashing
- Rotting OrangesmediumGraphsArrays & Hashing
- Surrounded RegionsmediumGraphsArrays & Hashing
- Walls and GatesmediumGraphsArrays & Hashing
- Accounts MergemediumGraphsStrings
- Distance to Nearest ZeromediumArrays & Hashing
- Minimum Height TreesmediumGraphs
- Lowest Common Ancestor of a Binary TreemediumTrees
- Web CrawlermediumGraphsDesign
- Binary Tree Maximum Path SumhardTreesDynamic Programming
- Serialize and Deserialize Binary TreehardTreesDesign
- Word Search IIhardBacktrackingTrees
- Alien DictionaryhardGraphsStrings
- Longest Increasing Path in a MatrixhardGraphsDynamic Programming
- Reconstruct ItineraryhardBacktrackingGraphs
- Swim in Rising WaterhardBinary SearchHeaps
- Word LadderhardGraphsStrings
- Trapping Rain WaterhardStackHeaps
The idea
Use breadth-first search when the first time you reach a cell is the shortest way there. Use depth-first search to cover a whole region or try every path.
Mark a cell visited when you queue it, not when you pop it. Otherwise the same cell enters the queue many times.
from collections import deque
queue = deque([start])
seen = {start} # mark on entry, not on exit
steps = 0
while queue:
for _ in range(len(queue)): # one ring at a time
r, c = queue.popleft()
if (r, c) == goal:
return steps
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nxt = (r + dr, c + dc)
if in_bounds(nxt) and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
steps += 1
return -1 # the goal was never reachedWhere it goes wrong
- Recursing so deep that a big grid overflows the call stack.
- Marking a cell visited too late.
- Leaving out the bounds check at the edge of the grid.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
Where Coco comes in
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.
Questions people ask
- When does BFS beat DFS?
- When every edge costs the same and you want the fewest steps. The first time breadth-first search reaches a node is the shortest way.
- Do I need a visited set on a tree?
- No. A tree has no cycles, so walking from parent to child reaches every node once. A grid or a graph does need one.
Meet these next
Fin and Coco are characters, not people. strongyes.io is independent. Leo builds it with AI agents.
