Depth-First Search Coding Problems: 50 Questions with Solutions
50 depth-first search coding problems — 1 easy · 41 medium · 8 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 7-day plan.
- Problems: 50
- By difficulty: 1 easy · 41 medium · 8 hard
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
- Cost: Free on every plan; sign in to run and submit
Depth-first search follows one path as far as it goes before backing up: recursion over a tree, flood fill over a grid, connected components over a graph, and the explicit stack that replaces recursion when depth is a concern. The problems here practise the visited bookkeeping, the base cases, and the choice between returning a value up the recursion and accumulating one in place.
How depth-first search works, step by step
edges = A–B, A–C, B–D, B–E, C–F, D–E; start = A- Depth-first search follows one path as deep as it goes before trying another. dfs(A) is called: A is discovered 1st and pushed on the call stack.
- In dfs(A), B is unvisited, so dfs(B) is pushed on top and B is discovered 2nd. A's other neighbours wait until B's whole branch is finished.
- In dfs(B), D is unvisited, so dfs(D) is pushed on top and D is discovered 3rd. The stack always holds the path from A down to the node being explored.
- In dfs(D), E is unvisited, so dfs(E) is pushed on top and E is discovered 4th. The path is now A → B → D → E.
- E–B leads back to B, still on the stack: a back edge, which means the graph has a cycle, so it is not followed. Nothing unvisited is left around E: dfs(E) is popped and the search backtracks to D.
- Back in dfs(D), nothing unvisited is left: dfs(D) is popped and the search backtracks to B.
- Back in dfs(B), E is already finished (reached through D), so nothing unvisited is left: dfs(B) is popped and the search backtracks to A.
- Back in dfs(A), C is unvisited, so dfs(C) is pushed on top and C is discovered 5th. The search goes deep again from here.
- In dfs(C), F is unvisited, so dfs(F) is pushed on top and F is discovered 6th. That is every node found, but the open calls still have to return.
- F's only neighbour is C, its caller, so dfs(F) returns at once and the search backtracks to C.
- Back in dfs(C), nothing unvisited is left: dfs(C) is popped and the search backtracks to A.
- dfs(A) returns and the stack is empty. Discovery order: A, B, D, E, C, F; the teal edges are the calls made, the dashed one the back edge. Each node and edge is handled once: O(V + E).
Depth-First Search study plan
11 of the 50 Depth-First Search problems (1 easy, 7 medium and 3 hard) over 7 days, about 7 h 10 min in all — the pattern first, then easiest to hardest. After that, the other 39 in the full list below are practice at your own pace. Then move on to Topological Sort.
Day 1
Learn the pattern: read the essentials and step through the walkthrough above, then solve these 2.
- Flood Fill Easy
- Word Search Medium
Day 2
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Number of Islands Medium
- Max Area of Island Medium
Day 3
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Keys and Rooms Medium
- Number of Provinces Medium
Day 4
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Pacific Atlantic Water Flow Medium
- Surrounded Regions Medium
Day 5
Hard problems: the pattern combined with a second idea. Give each a full attempt before reading the editorial.
- Swim in Rising Water Hard
Day 6
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Day 7
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Depth-First Search: the essentials
When to reach for it
Reachability, connected regions and properties of whole paths: count the islands, measure a region, decide whether a path exists, find a cycle in a directed graph. DFS does not give shortest paths in an unweighted graph, but it needs less bookkeeping than BFS, and its finishing order is what cycle detection and topological sorting rely on.
The pattern
Mark the node, then recurse into each unmarked neighbour. On a grid that may be modified, marking can mean overwriting the cell, land becoming water. Directed cycle detection needs three states, not two: unvisited, on the current path, and finished — reaching a node that is still on the current path closes a cycle.
def count_islands(grid):
rows, cols = len(grid), len(grid[0])
def sink(r, c): # 1 if (r, c) was unvisited land
if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != 1:
return 0
grid[r][c] = 0 # mark before recursing
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
sink(r + dr, c + dc)
return 1
return sum(sink(r, c) for r in range(rows) for c in range(cols))
Cost
O(V + E) time. Space is the recursion depth, up to O(V) — a million frames on a 1000 × 1000 grid of land.
Common mistakes
- Overflowing the call stack: Python stops at 1,000 frames by default, and other languages at whatever stack the process has. Use an explicit stack when depth can reach the input size.
- Marking a node after the recursive calls instead of before, so two paths enter it.
- One visited set for directed cycle detection, which mistakes a node finished on another branch for a cycle.
- Forgetting to unmark when the question is about paths rather than reachability — that is Backtracking.
Start with
- Flood Fill: one region from one cell.
- Number of Islands: one search per unvisited region.
- Number of Provinces: components from an adjacency matrix.
All depth-first search problems
Easy (1)
- Flood Fill Array, Matrix, Breadth-First Search
Medium (41)
- Course Schedule IV Graph, Topological Sort, Breadth-First Search
- Detonate the Maximum Bombs Array, Math, Graph
- Loud and Rich Array, Graph, Topological Sort
- Number of Nodes in the Sub-Tree With the Same Label Hash Table, Tree, Graph
- Minimum Fuel Cost to Report to the Capital Tree, Graph, Breadth-First Search
- Count the Number of Complete Components Graph, Union Find, Breadth-First Search
- Minimum Score of a Path Between Two Cities Graph, Union Find, Breadth-First Search
- Reachable Nodes With Restrictions Array, Tree, Graph
- Maximum Number of Fish in a Grid Array, Matrix, Breadth-First Search
- Check Knight Tour Configuration Array, Matrix, Simulation
- Find All Groups of Farmland Array, Matrix, Breadth-First Search
- Where Will the Ball Fall Array, Matrix, Simulation
- Word Search Array, String, Backtracking
- Pacific Atlantic Water Flow Array, Breadth-First Search, Matrix
- Jump Game III Array, Breadth-First Search
- Count Unreachable Pairs of Nodes in an Undirected Graph Breadth-First Search, Union Find, Graph
- Find Closest Node to Given Two Nodes Graph
- Path With Minimum Effort Array, Binary Search, Breadth-First Search
- Time Needed to Inform All Employees Tree, Breadth-First Search
- Reorder Routes to Make All Paths Lead to the City Zero Breadth-First Search, Graph
- Possible Bipartition Breadth-First Search, Union Find, Graph
- Minimum Height Trees Breadth-First Search, Graph, Topological Sort
- Detect Cycles in 2D Grid Array, Breadth-First Search, Union Find
- Number of Distinct Islands Array, Hash Table, Breadth-First Search
- Shortest Bridge Array, Breadth-First Search, Matrix
- Number of Operations to Make Network Connected Breadth-First Search, Union Find, Graph
- Count Sub Islands Array, Breadth-First Search, Union Find
- Number of Enclaves Array, Breadth-First Search, Union Find
- Find Eventual Safe States Breadth-First Search, Graph, Topological Sort
- All Paths From Source to Target Backtracking, Breadth-First Search, Graph
- Keys and Rooms Breadth-First Search, Graph
- Is Graph Bipartite? Breadth-First Search, Union Find, Graph
- Graph Valid Tree Breadth-First Search, Union Find, Graph
- Number of Connected Components in an Undirected Graph Breadth-First Search, Union Find, Graph
- Count Servers that Communicate Array, Breadth-First Search, Union Find
- Number of Closed Islands Array, Breadth-First Search, Union Find
- Surrounded Regions Array, Breadth-First Search, Union Find
- Course Schedule Graph, Topological Sort
- Number of Provinces Graph, Union Find
- Max Area of Island Array, Matrix
- Number of Islands Array, Matrix, Breadth-First Search
Hard (8)
- Minimum Number of Days to Disconnect Island Array, Matrix, Breadth-First Search
- Number of Increasing Paths in a Grid Array, Matrix, Dynamic Programming
- Find All People With Secret Graph, Union Find, Breadth-First Search
- Critical Connections in a Network Graph, Biconnected Component
- Making A Large Island Array, Matrix, Breadth-First Search
- Longest Increasing Path in a Matrix Array, Matrix, Dynamic Programming
- Swim in Rising Water Array, Binary Search, Breadth-First Search
- Longest Cycle in a Graph Graph, Topological Sort
Companies that ask depth-first search problems
- Amazon 45 problems on depth-first search
- Google 43 problems on depth-first search
- Microsoft 13 problems on depth-first search
- Meta 12 problems on depth-first search
- Adobe 3 problems on depth-first search
- Bloomberg 2 problems on depth-first search
- Flipkart 2 problems on depth-first search
- Oracle 2 problems on depth-first search
- Salesforce 2 problems on depth-first search
- Uber 2 problems on depth-first search
- Accenture 1 problem on depth-first search
- Apple 1 problem on depth-first search
Next topic: Topological Sort