Depth-First Search Pattern: Template + 366 LeetCode Problems
Follow one path to its end before trying the next — the default way to explore a graph.
- 41 Easy
- 214 Medium
- 111 Hard
- O(V + E) time
What the depth-first search pattern is
Depth-first search commits to one branch and follows it to exhaustion before backing up, which makes it the right traversal whenever the question is about a whole component rather than about distance. Recursion is the natural expression because the call stack already is the traversal stack, but the recursion depth equals the longest path — enough to blow Python's default limit on a large grid, which is when the explicit-stack form earns its keep. The bug that costs the most time is marking nodes seen at the wrong moment: mark on discovery, when the node is first pushed or first entered, never when it is popped, or a node reachable by two edges gets queued twice and the traversal degenerates. For cycle detection in a directed graph, a two-state seen set is not enough — you need three, because a node already finished is not the same thing as a node still on the current path, and only the second means a cycle.
When to use it
- You need everything reachable from a node: a connected component, an island, an enclosed region.
- The problem is about paths, subtree aggregates, or values computed from children.
- You are detecting a cycle in a directed graph, or classifying edges.
- The graph is deep and narrow rather than wide, so a queue would hold more than the stack does.
The depth-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 366 problems listed below.
def dfs(graph, start):
seen = {start}
stack = [start]
order = []
while stack:
node = stack.pop()
order.append(node)
for neighbour in graph[node]:
if neighbour not in seen:
seen.add(neighbour) # mark on PUSH, not on pop
stack.append(neighbour)
return orderComplexity characteristics
- Time
- O(V + E)
- Auxiliary space
- O(V)
Every node is marked seen once and every edge is examined once from each endpoint, so the traversal is linear in the size of the graph — on an r × c grid that is O(r·c), with four edges per cell. The space is the seen set plus the stack, and the stack holds the longest path in the graph, which is why the recursive form overflows Python's default recursion limit on a large grid while the explicit-stack form does not.
All 366 depth-first search LeetCode problems
Every problem in the library the depth-first search pattern applies to, grouped by LeetCode's own difficulty rating. 272 of the 366 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.
Easy (41)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 94 | Binary Tree Inorder Traversal | Easy | Stack, Tree, Depth-First Search +1 |
| 100 | Same Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 101 | Symmetric Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 104 | Maximum Depth of Binary Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 110 | Balanced Binary Tree | Easy | Tree, Depth-First Search, Binary Tree |
| 111 | Minimum Depth of Binary Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 112 | Path Sum | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 144 | Binary Tree Preorder Traversal | Easy | Stack, Tree, Depth-First Search +1 |
| 145 | Binary Tree Postorder Traversal | Easy | Stack, Tree, Depth-First Search +1 |
| 226 | Invert Binary Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 257 | Binary Tree Paths | Easy | Tree, Depth-First Search, String +2 |
| 404 | Sum of Left Leaves | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 463 | Island Perimeter | Easy | Depth-First Search, Breadth-First Search, Array +1 |
| 501 | Find Mode in Binary Search Tree | Easy | Tree, Depth-First Search, Binary Search Tree +1 |
| 530 | Minimum Absolute Difference in BST | Easy | Tree, Depth-First Search, Breadth-First Search +2 |
| 543 | Diameter of Binary Tree | Easy | Tree, Depth-First Search, Binary Tree |
| 559 | Maximum Depth of N-ary Tree | Easy | Tree, Depth-First Search, Breadth-First Search |
| 563 | Binary Tree Tilt | Easy | Tree, Depth-First Search, Binary Tree |
| 572 | Subtree of Another Tree | Easy | Tree, Depth-First Search, Binary Tree +2 |
| 589 | N-ary Tree Preorder Traversal | Easy | Stack, Tree, Depth-First Search |
| 590 | N-ary Tree Postorder Traversal | Easy | Stack, Tree, Depth-First Search |
| 617 | Merge Two Binary Trees | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 637 | Average of Levels in Binary Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 653 | Two Sum IV - Input is a BST | Easy | Tree, Depth-First Search, Breadth-First Search +4 |
| 671 | Second Minimum Node In a Binary Tree | Easy | Tree, Depth-First Search, Binary Tree |
| 733 | Flood Fill | Easy | Depth-First Search, Breadth-First Search, Array +1 |
| 872 | Leaf-Similar Trees | Easy | Tree, Depth-First Search, Binary Tree |
| 270 | Closest Binary Search Tree ValuePremium | Easy | Tree, Depth-First Search, Binary Search Tree +2 |
| 783 | Minimum Distance Between BST Nodes | Easy | Tree, Depth-First Search, Breadth-First Search +2 |
| 897 | Increasing Order Search Tree | Easy | Stack, Tree, Depth-First Search +2 |
| 938 | Range Sum of BST | Easy | Tree, Depth-First Search, Binary Search Tree +1 |
| 965 | Univalued Binary Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 993 | Cousins in Binary Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 997 | Find the Town Judge | Easy | Graph, Array, Hash Table |
| 1022 | Sum of Root To Leaf Binary Numbers | Easy | Tree, Depth-First Search, Binary Tree |
| 1379 | Find a Corresponding Node of a Binary Tree in a Clone of That Tree | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 1469 | Find All The Lonely NodesPremium | Easy | Tree, Depth-First Search, Breadth-First Search +1 |
| 1791 | Find Center of Star Graph | Easy | Graph |
| 1971 | Find if Path Exists in Graph | Easy | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2331 | Evaluate Boolean Binary Tree | Easy | Tree, Depth-First Search, Binary Tree |
| 2689 | Extract Kth Character From The Rope TreePremium | Easy | Tree, Depth-First Search, Binary Tree |
Medium (214)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 79 | Word Search | Medium | Depth-First Search, Array, String +2 |
| 98 | Validate Binary Search Tree | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 99 | Recover Binary Search Tree | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 113 | Path Sum II | Medium | Tree, Depth-First Search, Backtracking +1 |
| 114 | Flatten Binary Tree to Linked List | Medium | Stack, Tree, Depth-First Search +2 |
| 116 | Populating Next Right Pointers in Each Node | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 117 | Populating Next Right Pointers in Each Node II | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 129 | Sum Root to Leaf Numbers | Medium | Tree, Depth-First Search, Binary Tree |
| 130 | Surrounded Regions | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 133 | Clone Graph | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 199 | Binary Tree Right Side View | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 200 | Number of Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 207 | Course Schedule | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 210 | Course Schedule II | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 211 | Design Add and Search Words Data Structure | Medium | Depth-First Search, Design, Trie +1 |
| 230 | Kth Smallest Element in a BST | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 235 | Lowest Common Ancestor of a Binary Search Tree | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 236 | Lowest Common Ancestor of a Binary Tree | Medium | Tree, Depth-First Search, Binary Tree |
| 310 | Minimum Height Trees | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 337 | House Robber III | Medium | Tree, Depth-First Search, Dynamic Programming +1 |
| 341 | Flatten Nested List Iterator | Medium | Stack, Tree, Depth-First Search +3 |
| 365 | Water and Jug Problem | Medium | Depth-First Search, Breadth-First Search, Math |
| 385 | Mini Parser | Medium | Stack, Depth-First Search, String |
| 386 | Lexicographical Numbers | Medium | Depth-First Search, Trie |
| 388 | Longest Absolute File Path | Medium | Stack, Depth-First Search, String |
| 399 | Evaluate Division | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 417 | Pacific Atlantic Water Flow | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 419 | Battleships in a Board | Medium | Depth-First Search, Array, Matrix |
| 430 | Flatten a Multilevel Doubly Linked List | Medium | Depth-First Search, Linked List, Doubly-Linked List |
| 437 | Path Sum III | Medium | Tree, Depth-First Search, Binary Tree |
| 449 | Serialize and Deserialize BST | Medium | Tree, Depth-First Search, Breadth-First Search +4 |
| 508 | Most Frequent Subtree Sum | Medium | Tree, Depth-First Search, Hash Table +1 |
| 513 | Find Bottom Left Tree Value | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 515 | Find Largest Value in Each Tree Row | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 529 | Minesweeper | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 538 | Convert BST to Greater Tree | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 547 | Number of Provinces | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 565 | Array Nesting | Medium | Depth-First Search, Array |
| 606 | Construct String from Binary Tree | Medium | Tree, Depth-First Search, String +1 |
| 623 | Add One Row to Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 652 | Find Duplicate Subtrees | Medium | Tree, Depth-First Search, Hash Table +1 |
| 655 | Print Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 662 | Maximum Width of Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 669 | Trim a Binary Search Tree | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 672 | Bulb Switcher II | Medium | Bit Manipulation, Depth-First Search, Breadth-First Search +1 |
| 676 | Implement Magic Dictionary | Medium | Depth-First Search, Design, Trie +2 |
| 684 | Redundant Connection | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 687 | Longest Univalue Path | Medium | Tree, Depth-First Search, Binary Tree |
| 690 | Employee Importance | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 695 | Max Area of Island | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 721 | Accounts Merge | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 743 | Network Delay Time | Medium | Depth-First Search, Breadth-First Search, Graph +2 |
| 787 | Cheapest Flights Within K Stops | Medium | Depth-First Search, Breadth-First Search, Graph +3 |
| 841 | Keys and Rooms | Medium | Depth-First Search, Breadth-First Search, Graph |
| 1161 | Maximum Level Sum of a Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1372 | Longest ZigZag Path in a Binary Tree | Medium | Tree, Depth-First Search, Dynamic Programming +1 |
| 1448 | Count Good Nodes in Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1466 | Reorder Routes to Make All Paths Lead to the City Zero | Medium | Depth-First Search, Breadth-First Search, Graph |
| 1584 | Min Cost to Connect All Points | Medium | Union Find, Graph, Array +1 |
| 156 | Binary Tree Upside DownPremium | Medium | Tree, Depth-First Search, Binary Tree |
| 250 | Count Univalue SubtreesPremium | Medium | Tree, Depth-First Search, Binary Tree |
| 261 | Graph Valid TreePremium | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 277 | Find the CelebrityPremium | Medium | Graph, Two Pointers, Interactive |
| 285 | Inorder Successor in BSTPremium | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 298 | Binary Tree Longest Consecutive SequencePremium | Medium | Tree, Depth-First Search, Binary Tree |
| 314 | Binary Tree Vertical Order TraversalPremium | Medium | Tree, Depth-First Search, Breadth-First Search +3 |
| 323 | Number of Connected Components in an Undirected GraphPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 333 | Largest BST SubtreePremium | Medium | Tree, Depth-First Search, Binary Search Tree +2 |
| 339 | Nested List Weight SumPremium | Medium | Depth-First Search, Breadth-First Search |
| 364 | Nested List Weight Sum IIPremium | Medium | Stack, Depth-First Search, Breadth-First Search |
| 366 | Find Leaves of Binary TreePremium | Medium | Tree, Depth-First Search, Binary Tree |
| 426 | Convert Binary Search Tree to Sorted Doubly Linked ListPremium | Medium | Stack, Tree, Depth-First Search +4 |
| 444 | Sequence ReconstructionPremium | Medium | Graph, Topological Sort, Array |
| 490 | The MazePremium | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 505 | The Maze IIPremium | Medium | Depth-First Search, Breadth-First Search, Graph +4 |
| 536 | Construct Binary Tree from StringPremium | Medium | Stack, Tree, Depth-First Search +2 |
| 545 | Boundary of Binary TreePremium | Medium | Tree, Depth-First Search, Binary Tree |
| 549 | Binary Tree Longest Consecutive Sequence IIPremium | Medium | Tree, Depth-First Search, Binary Tree |
| 582 | Kill ProcessPremium | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 663 | Equal Tree PartitionPremium | Medium | Tree, Depth-First Search, Binary Tree |
| 666 | Path Sum IVPremium | Medium | Tree, Depth-First Search, Array +2 |
| 694 | Number of Distinct IslandsPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 737 | Sentence Similarity IIPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 742 | Closest Leaf in a Binary TreePremium | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 785 | Is Graph Bipartite? | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 797 | All Paths From Source to Target | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 802 | Find Eventual Safe States | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 814 | Binary Tree Pruning | Medium | Tree, Depth-First Search, Binary Tree |
| 851 | Loud and Rich | Medium | Depth-First Search, Graph, Topological Sort +1 |
| 863 | All Nodes Distance K in Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 865 | Smallest Subtree with all the Deepest Nodes | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 886 | Possible Bipartition | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 934 | Shortest Bridge | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 947 | Most Stones Removed with Same Row or Column | Medium | Depth-First Search, Union Find, Graph +1 |
| 951 | Flip Equivalent Binary Trees | Medium | Tree, Depth-First Search, Binary Tree |
| 959 | Regions Cut By Slashes | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 971 | Flip Binary Tree To Match Preorder Traversal | Medium | Tree, Depth-First Search, Binary Tree |
| 979 | Distribute Coins in Binary Tree | Medium | Tree, Depth-First Search, Binary Tree |
| 988 | Smallest String Starting From Leaf | Medium | Tree, Depth-First Search, String +2 |
| 990 | Satisfiability of Equality Equations | Medium | Union Find, Graph, Array +1 |
| 1020 | Number of Enclaves | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1026 | Maximum Difference Between Node and Ancestor | Medium | Tree, Depth-First Search, Binary Tree |
| 1034 | Coloring A Border | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 1038 | Binary Search Tree to Greater Sum Tree | Medium | Tree, Depth-First Search, Binary Search Tree +1 |
| 1042 | Flower Planting With No Adjacent | Medium | Depth-First Search, Breadth-First Search, Graph |
| 1059 | All Paths from Source Lead to DestinationPremium | Medium | Graph, Topological Sort |
| 1080 | Insufficient Nodes in Root to Leaf Paths | Medium | Tree, Depth-First Search, Binary Tree |
| 1102 | Path With Maximum Minimum ValuePremium | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1110 | Delete Nodes And Return Forest | Medium | Tree, Depth-First Search, Array +2 |
| 1120 | Maximum Average SubtreePremium | Medium | Tree, Depth-First Search, Binary Tree |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 1129 | Shortest Path with Alternating Colors | Medium | Breadth-First Search, Graph |
| 1135 | Connecting Cities With Minimum CostPremium | Medium | Union Find, Graph, Minimum Spanning Tree +1 |
| 1136 | Parallel CoursesPremium | Medium | Graph, Topological Sort |
| 1145 | Binary Tree Coloring Game | Medium | Tree, Depth-First Search, Binary Tree |
| 1202 | Smallest String With Swaps | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1214 | Two Sum BSTsPremium | Medium | Stack, Tree, Depth-First Search +4 |
| 1233 | Remove Sub-Folders from the Filesystem | Medium | Depth-First Search, Trie, Array +1 |
| 1236 | Web CrawlerPremium | Medium | Depth-First Search, Breadth-First Search, String +1 |
| 1242 | Web Crawler MultithreadedPremium | Medium | Depth-First Search, Breadth-First Search, Concurrency |
| 1245 | Tree DiameterPremium | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 1254 | Number of Closed Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1257 | Smallest Common RegionPremium | Medium | Tree, Depth-First Search, Breadth-First Search +3 |
| 1261 | Find Elements in a Contaminated Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +3 |
| 1267 | Count Servers that Communicate | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 1273 | Delete Tree NodesPremium | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1302 | Deepest Leaves Sum | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1305 | All Elements in Two Binary Search Trees | Medium | Tree, Depth-First Search, Binary Search Tree +2 |
| 1306 | Jump Game III | Medium | Depth-First Search, Breadth-First Search, Array |
| 1311 | Get Watched Videos by Your Friends | Medium | Breadth-First Search, Graph, Array +2 |
| 1315 | Sum of Nodes with Even-Valued Grandparent | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1319 | Number of Operations to Make Network Connected | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 1325 | Delete Leaves With a Given Value | Medium | Tree, Depth-First Search, Binary Tree |
| 1334 | Find the City With the Smallest Number of Neighbors at a Threshold Distance | Medium | Graph, Dynamic Programming, Shortest Path |
| 1339 | Maximum Product of Splitted Binary Tree | Medium | Tree, Depth-First Search, Binary Tree |
| 1361 | Validate Binary Tree Nodes | Medium | Tree, Depth-First Search, Breadth-First Search +3 |
| 1367 | Linked List in Binary Tree | Medium | Tree, Depth-First Search, Linked List +1 |
| 1376 | Time Needed to Inform All Employees | Medium | Tree, Depth-First Search, Breadth-First Search |
| 1382 | Balance a Binary Search Tree | Medium | Greedy, Tree, Depth-First Search +3 |
| 1391 | Check if There is a Valid Path in a Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1430 | Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary TreePremium | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1443 | Minimum Time to Collect All Apples in a Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1457 | Pseudo-Palindromic Paths in a Binary Tree | Medium | Bit Manipulation, Tree, Depth-First Search +2 |
| 1462 | Course Schedule IV | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 1485 | Clone Binary Tree With Random PointerPremium | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 1490 | Clone N-ary TreePremium | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 1506 | Find Root of N-Ary TreePremium | Medium | Bit Manipulation, Tree, Depth-First Search +1 |
| 1514 | Path with Maximum Probability | Medium | Graph, Array, Shortest Path +1 |
| 1519 | Number of Nodes in the Sub-Tree With the Same Label | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 1522 | Diameter of N-Ary TreePremium | Medium | Tree, Depth-First Search |
| 1530 | Number of Good Leaf Nodes Pairs | Medium | Tree, Depth-First Search, Binary Tree |
| 1557 | Minimum Number of Vertices to Reach All Nodes | Medium | Graph |
| 1559 | Detect Cycles in 2D Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1600 | Throne Inheritance | Medium | Tree, Depth-First Search, Design +1 |
| 1612 | Check If Two Expression Trees are EquivalentPremium | Medium | Tree, Depth-First Search, Hash Table +2 |
| 1615 | Maximal Network Rank | Medium | Graph |
| 1625 | Lexicographically Smallest String After Applying Operations | Medium | Depth-First Search, Breadth-First Search, String +1 |
| 1631 | Path With Minimum Effort | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1644 | Lowest Common Ancestor of a Binary Tree IIPremium | Medium | Tree, Depth-First Search, Binary Tree |
| 1660 | Correct a Binary TreePremium | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 1666 | Change the Root of a Binary TreePremium | Medium | Tree, Depth-First Search, Binary Tree |
| 1676 | Lowest Common Ancestor of a Binary Tree IVPremium | Medium | Tree, Depth-First Search, Hash Table +1 |
| 1722 | Minimize Hamming Distance After Swap Operations | Medium | Depth-First Search, Union Find, Array |
| 1740 | Find Distance in a Binary TreePremium | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 1743 | Restore the Array From Adjacent Pairs | Medium | Depth-First Search, Array, Hash Table |
| 1778 | Shortest Path in a Hidden GridPremium | Medium | Depth-First Search, Breadth-First Search, Array +2 |
| 1786 | Number of Restricted Paths From First to Last Node | Medium | Graph, Topological Sort, Dynamic Programming +2 |
| 1810 | Minimum Path Cost in a Hidden GridPremium | Medium | Depth-First Search, Breadth-First Search, Graph +5 |
| 1820 | Maximum Number of Accepted InvitationsPremium | Medium | Depth-First Search, Graph, Array +1 |
| 1858 | Longest Word With All PrefixesPremium | Medium | Depth-First Search, Trie, Array +1 |
| 1905 | Count Sub Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1973 | Count Nodes Equal to Sum of DescendantsPremium | Medium | Tree, Depth-First Search, Binary Tree |
| 1976 | Number of Ways to Arrive at Destination | Medium | Graph, Topological Sort, Dynamic Programming +1 |
| 1992 | Find All Groups of Farmland | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 1993 | Operations on Tree | Medium | Tree, Depth-First Search, Breadth-First Search +3 |
| 2039 | The Time When the Network Becomes Idle | Medium | Breadth-First Search, Graph, Array |
| 2049 | Count Nodes With the Highest Score | Medium | Tree, Depth-First Search, Array +1 |
| 2077 | Paths in Maze That Lead to Same RoomPremium | Medium | Graph |
| 2093 | Minimum Cost to Reach City With DiscountsPremium | Medium | Graph, Shortest Path, Heap (Priority Queue) |
| 2096 | Step-By-Step Directions From a Binary Tree Node to Another | Medium | Tree, Depth-First Search, String +1 |
| 2101 | Detonate the Maximum Bombs | Medium | Depth-First Search, Breadth-First Search, Graph +3 |
| 2115 | Find All Possible Recipes from Given Supplies | Medium | Graph, Topological Sort, Array +2 |
| 2192 | All Ancestors of a Node in a Directed Acyclic Graph | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 2265 | Count Nodes Equal to Average of Subtree | Medium | Tree, Depth-First Search, Binary Tree |
| 2285 | Maximum Total Importance of Roads | Medium | Greedy, Graph, Sorting +1 |
| 2297 | Jump Game VIIIPremium | Medium | Stack, Graph, Array +3 |
| 2316 | Count Unreachable Pairs of Nodes in an Undirected Graph | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2359 | Find Closest Node to Given Two Nodes | Medium | Depth-First Search, Graph |
| 2368 | Reachable Nodes With Restrictions | Medium | Tree, Depth-First Search, Breadth-First Search +4 |
| 2374 | Node With Highest Edge Score | Medium | Graph, Hash Table |
| 2378 | Choose Edges to Maximize Score in a TreePremium | Medium | Tree, Depth-First Search, Dynamic Programming |
| 2385 | Amount of Time for Binary Tree to Be Infected | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 2415 | Reverse Odd Levels of Binary Tree | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 2445 | Number of Nodes With Value OnePremium | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 2467 | Most Profitable Path in a Tree | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 2473 | Minimum Cost to Buy ApplesPremium | Medium | Graph, Array, Shortest Path +1 |
| 2476 | Closest Nodes Queries in a Binary Search Tree | Medium | Tree, Depth-First Search, Binary Search Tree +3 |
| 2477 | Minimum Fuel Cost to Report to the Capital | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 2492 | Minimum Score of a Path Between Two Cities | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2497 | Maximum Star Sum of a Graph | Medium | Greedy, Graph, Array +2 |
| 2556 | Disconnect Path in a Binary Matrix by at Most One Flip | Medium | Depth-First Search, Breadth-First Search, Array +2 |
| 2596 | Check Knight Tour Configuration | Medium | Depth-First Search, Breadth-First Search, Array +2 |
| 2641 | Cousins in Binary Tree II | Medium | Tree, Depth-First Search, Breadth-First Search +2 |
| 2658 | Maximum Number of Fish in a Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 2662 | Minimum Cost of a Path With Special Roads | Medium | Graph, Array, Shortest Path +1 |
| 2685 | Count the Number of Complete Components | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2737 | Find the Closest Marked NodePremium | Medium | Graph, Array, Shortest Path +1 |
| 2764 | Is Array a Preorder of Some Binary TreePremium | Medium | Stack, Tree, Depth-First Search +1 |
| 2773 | Height of Special Binary TreePremium | Medium | Tree, Depth-First Search, Breadth-First Search +1 |
| 2775 | Undefined to NullPremium | Medium | JavaScript |
| 2852 | Sum of Remoteness of All CellsPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 2924 | Find Champion II | Medium | Graph |
| 2925 | Maximum Score After Applying Operations on a Tree | Medium | Tree, Depth-First Search, Dynamic Programming |
| 2976 | Minimum Cost to Convert String I | Medium | Graph, Array, String +1 |
Hard (111)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 124 | Binary Tree Maximum Path Sum | Hard | Tree, Depth-First Search, Dynamic Programming +1 |
| 297 | Serialize and Deserialize Binary Tree | Hard | Tree, Depth-First Search, Breadth-First Search +3 |
| 329 | Longest Increasing Path in a Matrix | Hard | Depth-First Search, Breadth-First Search, Graph +5 |
| 332 | Reconstruct Itinerary | Hard | Depth-First Search, Graph, Eulerian Circuit |
| 472 | Concatenated Words | Hard | Depth-First Search, Trie, Array +3 |
| 514 | Freedom Trail | Hard | Depth-First Search, Breadth-First Search, String +1 |
| 685 | Redundant Connection II | Hard | Depth-First Search, Breadth-First Search, Union Find +1 |
| 749 | Contain Virus | Hard | Depth-First Search, Breadth-First Search, Array +2 |
| 778 | Swim in Rising Water | Hard | Depth-First Search, Breadth-First Search, Union Find +4 |
| 269 | Alien DictionaryPremium | Hard | Depth-First Search, Breadth-First Search, Graph +3 |
| 272 | Closest Binary Search Tree Value IIPremium | Hard | Stack, Tree, Depth-First Search +4 |
| 302 | Smallest Rectangle Enclosing Black PixelsPremium | Hard | Depth-First Search, Breadth-First Search, Array +2 |
| 428 | Serialize and Deserialize N-ary TreePremium | Hard | Tree, Depth-First Search, Breadth-First Search +1 |
| 431 | Encode N-ary Tree to Binary TreePremium | Hard | Tree, Depth-First Search, Breadth-First Search +2 |
| 499 | The Maze IIIPremium | Hard | Depth-First Search, Breadth-First Search, Graph +5 |
| 631 | Design Excel Sum FormulaPremium | Hard | Graph, Design, Topological Sort +4 |
| 642 | Design Search Autocomplete SystemPremium | Hard | Depth-First Search, Design, Trie +4 |
| 711 | Number of Distinct Islands IIPremium | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 753 | Cracking the Safe | Hard | Depth-First Search, Graph, Eulerian Circuit |
| 765 | Couples Holding Hands | Hard | Greedy, Depth-First Search, Breadth-First Search +2 |
| 827 | Making A Large Island | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 834 | Sum of Distances in Tree | Hard | Tree, Depth-First Search, Graph +1 |
| 839 | Similar String Groups | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 847 | Shortest Path Visiting All Nodes | Hard | Bit Manipulation, Breadth-First Search, Graph +2 |
| 882 | Reachable Nodes In Subdivided Graph | Hard | Graph, Shortest Path, Heap (Priority Queue) |
| 913 | Cat and Mouse | Hard | Graph, Topological Sort, Memoization +3 |
| 924 | Minimize Malware Spread | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 928 | Minimize Malware Spread II | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 968 | Binary Tree Cameras | Hard | Tree, Depth-First Search, Dynamic Programming +1 |
| 987 | Vertical Order Traversal of a Binary Tree | Hard | Tree, Depth-First Search, Breadth-First Search +3 |
| 1028 | Recover a Tree From Preorder Traversal | Hard | Tree, Depth-First Search, String +1 |
| 1036 | Escape a Large Maze | Hard | Depth-First Search, Breadth-First Search, Array +1 |
| 1153 | String Transforms Into Another StringPremium | Hard | Graph, Hash Table, String |
| 1168 | Optimize Water Distribution in a VillagePremium | Hard | Union Find, Graph, Minimum Spanning Tree +1 |
| 1192 | Critical Connections in a Network | Hard | Depth-First Search, Graph, Biconnected Component |
| 1203 | Sort Items by Groups Respecting Dependencies | Hard | Depth-First Search, Breadth-First Search, Graph +1 |
| 1298 | Maximum Candies You Can Get from Boxes | Hard | Breadth-First Search, Graph, Array |
| 1368 | Minimum Cost to Make at Least One Valid Path in a Grid | Hard | Breadth-First Search, Graph, Array +3 |
| 1373 | Maximum Sum BST in Binary Tree | Hard | Tree, Depth-First Search, Binary Search Tree +2 |
| 1377 | Frog Position After T Seconds | Hard | Tree, Depth-First Search, Breadth-First Search +1 |
| 1483 | Kth Ancestor of a Tree Node | Hard | Bit Manipulation, Tree, Depth-First Search +4 |
| 1489 | Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree | Hard | Union Find, Graph, Minimum Spanning Tree +2 |
| 1494 | Parallel Courses II | Hard | Bit Manipulation, Graph, Dynamic Programming +1 |
| 1516 | Move Sub-Tree of N-Ary TreePremium | Hard | Tree, Depth-First Search |
| 1548 | The Most Similar Path in a GraphPremium | Hard | Graph, Dynamic Programming |
| 1568 | Minimum Number of Days to Disconnect Island | Hard | Depth-First Search, Breadth-First Search, Array +2 |
| 1579 | Remove Max Number of Edges to Keep Graph Fully Traversable | Hard | Union Find, Graph |
| 1591 | Strange Printer II | Hard | Graph, Topological Sort, Array +1 |
| 1632 | Rank Transform of a Matrix | Hard | Union Find, Graph, Topological Sort +3 |
| 1697 | Checking Existence of Edge Length Limited Paths | Hard | Union Find, Graph, Array +2 |
| 1719 | Number Of Ways To Reconstruct A Tree | Hard | Tree, Graph |
| 1724 | Checking Existence of Edge Length Limited Paths IIPremium | Hard | Union Find, Graph, Minimum Spanning Tree |
| 1728 | Cat and Mouse II | Hard | Graph, Topological Sort, Memoization +5 |
| 1761 | Minimum Degree of a Connected Trio in a Graph | Hard | Graph, Enumeration |
| 1766 | Tree of Coprimes | Hard | Tree, Depth-First Search, Array +2 |
| 1782 | Count Pairs Of Nodes | Hard | Graph, Array, Hash Table +4 |
| 1857 | Largest Color Value in a Directed Graph | Hard | Graph, Topological Sort, Memoization +3 |
| 1916 | Count Ways to Build Rooms in an Ant Colony | Hard | Tree, Graph, Topological Sort +3 |
| 1928 | Minimum Cost to Reach Destination in Time | Hard | Graph, Array, Dynamic Programming |
| 1932 | Merge BSTs to Create Single BST | Hard | Tree, Depth-First Search, Hash Table +2 |
| 1938 | Maximum Genetic Difference Query | Hard | Bit Manipulation, Depth-First Search, Trie +2 |
| 1970 | Last Day Where You Can Still Cross | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 2003 | Smallest Missing Genetic Value in Each Subtree | Hard | Tree, Depth-First Search, Union Find +1 |
| 2045 | Second Minimum Time to Reach Destination | Hard | Breadth-First Search, Graph, Shortest Path |
| 2050 | Parallel Courses III | Hard | Graph, Topological Sort, Array +1 |
| 2065 | Maximum Path Quality of a Graph | Hard | Graph, Array, Backtracking |
| 2076 | Process Restricted Friend Requests | Hard | Union Find, Graph |
| 2092 | Find All People With Secret | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 2097 | Valid Arrangement of Pairs | Hard | Depth-First Search, Graph, Eulerian Circuit |
| 2123 | Minimum Operations to Remove Adjacent Ones in MatrixPremium | Hard | Graph, Array, Matrix |
| 2127 | Maximum Employees to Be Invited to a Meeting | Hard | Depth-First Search, Graph, Topological Sort |
| 2203 | Minimum Weighted Subgraph With the Required Paths | Hard | Graph, Shortest Path |
| 2204 | Distance to a Cycle in Undirected GraphPremium | Hard | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2242 | Maximum Score of a Node Sequence | Hard | Graph, Array, Enumeration +1 |
| 2246 | Longest Path With Different Adjacent Characters | Hard | Tree, Depth-First Search, Graph +3 |
| 2247 | Maximum Cost of Trip With K HighwaysPremium | Hard | Bit Manipulation, Graph, Dynamic Programming +1 |
| 2277 | Closest Node to Path in TreePremium | Hard | Tree, Depth-First Search, Breadth-First Search +1 |
| 2290 | Minimum Obstacle Removal to Reach Corner | Hard | Breadth-First Search, Graph, Array +3 |
| 2307 | Check for Contradictions in EquationsPremium | Hard | Depth-First Search, Union Find, Graph +1 |
| 2313 | Minimum Flips in Binary Tree to Get ResultPremium | Hard | Tree, Depth-First Search, Dynamic Programming +1 |
| 2322 | Minimum Score After Removals on a Tree | Hard | Bit Manipulation, Tree, Depth-First Search +1 |
| 2328 | Number of Increasing Paths in a Grid | Hard | Depth-First Search, Breadth-First Search, Graph +5 |
| 2360 | Longest Cycle in a Graph | Hard | Depth-First Search, Breadth-First Search, Graph +1 |
| 2371 | Minimize Maximum Value in a GridPremium | Hard | Union Find, Graph, Topological Sort +3 |
| 2392 | Build a Matrix With Conditions | Hard | Graph, Topological Sort, Array +1 |
| 2421 | Number of Good Paths | Hard | Tree, Union Find, Graph +3 |
| 2440 | Create Components With Same Value | Hard | Tree, Depth-First Search, Array +2 |
| 2458 | Height of Binary Tree After Subtree Removal Queries | Hard | Tree, Depth-First Search, Breadth-First Search +2 |
| 2479 | Maximum XOR of Two Non-Overlapping SubtreesPremium | Hard | Tree, Depth-First Search, Graph +1 |
| 2493 | Divide Nodes Into the Maximum Number of Groups | Hard | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2508 | Add Edges to Make Degrees of All Nodes Even | Hard | Graph, Hash Table |
| 2538 | Difference Between Maximum and Minimum Price Sum | Hard | Tree, Depth-First Search, Array +1 |
| 2577 | Minimum Time to Visit a Cell In a Grid | Hard | Breadth-First Search, Graph, Array +3 |
| 2581 | Count Number of Possible Root Nodes | Hard | Tree, Depth-First Search, Array +2 |
| 2603 | Collect Coins in a Tree | Hard | Tree, Graph, Topological Sort +1 |
| 2608 | Shortest Cycle in a Graph | Hard | Breadth-First Search, Graph |
| 2642 | Design Graph With Shortest Path Calculator | Hard | Graph, Design, Shortest Path +1 |
| 2646 | Minimize the Total Price of the Trips | Hard | Tree, Depth-First Search, Graph +2 |
| 2699 | Modify Graph Edge Weights | Hard | Graph, Shortest Path, Heap (Priority Queue) |
| 2714 | Find Shortest Path with K HopsPremium | Hard | Graph, Shortest Path, Heap (Priority Queue) |
| 2791 | Count Paths That Can Form a Palindrome in a Tree | Hard | Bit Manipulation, Tree, Depth-First Search +2 |
| 2792 | Count Nodes That Are Great EnoughPremium | Hard | Tree, Depth-First Search, Divide and Conquer +1 |
| 2846 | Minimum Edge Weight Equilibrium Queries in a Tree | Hard | Tree, Graph, Array +1 |
| 2858 | Minimum Edge Reversals So Every Node Is Reachable | Hard | Depth-First Search, Breadth-First Search, Graph +1 |
| 2867 | Count Valid Paths in a Tree | Hard | Tree, Depth-First Search, Math +2 |
| 2872 | Maximum Number of K-Divisible Components | Hard | Tree, Depth-First Search |
| 2876 | Count Visited Nodes in a Directed Graph | Hard | Graph, Memoization, Dynamic Programming |
| 2920 | Maximum Points After Collecting Coins From All Nodes | Hard | Bit Manipulation, Tree, Depth-First Search +3 |
| 2959 | Number of Possible Sets of Closing Branches | Hard | Bit Manipulation, Graph, Enumeration +2 |
| 2973 | Find Number of Coins to Place in Tree Nodes | Hard | Tree, Depth-First Search, Dynamic Programming +2 |
| 2977 | Minimum Cost to Convert String II | Hard | Graph, Trie, Array +3 |
Related patterns
Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.
Depth-First Search pattern FAQ
What is the depth-first search pattern?
Depth-first search commits to one branch and follows it to exhaustion before backing up, which makes it the right traversal whenever the question is about a whole component rather than about distance.
How many LeetCode problems use the depth-first search pattern?
This page lists 366 LeetCode problems that the depth-first search pattern applies to: 41 Easy, 214 Medium and 111 Hard. 272 of them carry a complete Python solution with complexity analysis.
What is the time complexity of the depth-first search pattern?
O(V + E) time and O(V) space. Every node is marked seen once and every edge is examined once from each endpoint, so the traversal is linear in the size of the graph — on an r × c grid that is O(r·c), with four edges per cell. The space is the seen set plus the stack, and the stack holds the longest path in the graph, which is why the recursive form overflows Python's default recursion limit on a large grid while the explicit-stack form does not.
When should I use the depth-first search pattern in an interview?
You need everything reachable from a node: a connected component, an island, an enclosed region. The problem is about paths, subtree aggregates, or values computed from children.
Which depth-first search problem should I start with?
LeetCode 94. Binary Tree Inorder Traversal 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 depth-first search?
Breadth-First Search, Backtracking, Tree Traversal, Matrix and Grid. 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.
Meet the depth-first search problem you did not practise
Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.