Pattern 11 of 22

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.

Easy
41
Medium
214
Hard
111
Time
O(V + E)

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.

PythonDepth-First Search template
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 order

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

Eyes only

Meet the depth-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 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.

Related LeetCode topics

Easy (41)

Easy problems
No.Problem
0094Binary Tree Inorder Traversal
0100Same Tree
0101Symmetric Tree
0104Maximum Depth of Binary Tree
0110Balanced Binary Tree
0111Minimum Depth of Binary Tree
0112Path Sum
0144Binary Tree Preorder Traversal
0145Binary Tree Postorder Traversal
0226Invert Binary Tree
0257Binary Tree Paths
0404Sum of Left Leaves
0463Island Perimeter
0501Find Mode in Binary Search Tree
0530Minimum Absolute Difference in BST
0543Diameter of Binary Tree
0559Maximum Depth of N-ary Tree
0563Binary Tree Tilt
0572Subtree of Another Tree
0589N-ary Tree Preorder Traversal
0590N-ary Tree Postorder Traversal
0617Merge Two Binary Trees
0637Average of Levels in Binary Tree
0653Two Sum IV - Input is a BST
0671Second Minimum Node In a Binary Tree
0733Flood Fill
0872Leaf-Similar Trees
0270Closest Binary Search Tree ValuePremium
0783Minimum Distance Between BST Nodes
0897Increasing Order Search Tree
0938Range Sum of BST
0965Univalued Binary Tree
0993Cousins in Binary Tree
0997Find the Town Judge
1022Sum of Root To Leaf Binary Numbers
1379Find a Corresponding Node of a Binary Tree in a Clone of That Tree
1469Find All The Lonely NodesPremium
1791Find Center of Star Graph
1971Find if Path Exists in Graph
2331Evaluate Boolean Binary Tree
2689Extract Kth Character From The Rope TreePremium

Medium (214)

Medium problems
No.Problem
0079Word Search
0098Validate Binary Search Tree
0099Recover Binary Search Tree
0113Path Sum II
0114Flatten Binary Tree to Linked List
0116Populating Next Right Pointers in Each Node
0117Populating Next Right Pointers in Each Node II
0129Sum Root to Leaf Numbers
0130Surrounded Regions
0133Clone Graph
0199Binary Tree Right Side View
0200Number of Islands
0207Course Schedule
0210Course Schedule II
0211Design Add and Search Words Data Structure
0230Kth Smallest Element in a BST
0235Lowest Common Ancestor of a Binary Search Tree
0236Lowest Common Ancestor of a Binary Tree
0310Minimum Height Trees
0337House Robber III
0341Flatten Nested List Iterator
0365Water and Jug Problem
0385Mini Parser
0386Lexicographical Numbers
0388Longest Absolute File Path
0399Evaluate Division
0417Pacific Atlantic Water Flow
0419Battleships in a Board
0430Flatten a Multilevel Doubly Linked List
0437Path Sum III
0449Serialize and Deserialize BST
0508Most Frequent Subtree Sum
0513Find Bottom Left Tree Value
0515Find Largest Value in Each Tree Row
0529Minesweeper
0538Convert BST to Greater Tree
0547Number of Provinces
0565Array Nesting
0606Construct String from Binary Tree
0623Add One Row to Tree
0652Find Duplicate Subtrees
0655Print Binary Tree
0662Maximum Width of Binary Tree
0669Trim a Binary Search Tree
0672Bulb Switcher II
0676Implement Magic Dictionary
0684Redundant Connection
0687Longest Univalue Path
0690Employee Importance
0695Max Area of Island
0721Accounts Merge
0743Network Delay Time
0787Cheapest Flights Within K Stops
0841Keys and Rooms
1161Maximum Level Sum of a Binary Tree
1372Longest ZigZag Path in a Binary Tree
1448Count Good Nodes in Binary Tree
1466Reorder Routes to Make All Paths Lead to the City Zero
1584Min Cost to Connect All Points
0156Binary Tree Upside DownPremium
0250Count Univalue SubtreesPremium
0261Graph Valid TreePremium
0277Find the CelebrityPremium
0285Inorder Successor in BSTPremium
0298Binary Tree Longest Consecutive SequencePremium
0314Binary Tree Vertical Order TraversalPremium
0323Number of Connected Components in an Undirected GraphPremium
0333Largest BST SubtreePremium
0339Nested List Weight SumPremium
0364Nested List Weight Sum IIPremium
0366Find Leaves of Binary TreePremium
0426Convert Binary Search Tree to Sorted Doubly Linked ListPremium
0444Sequence ReconstructionPremium
0490The MazePremium
0505The Maze IIPremium
0536Construct Binary Tree from StringPremium
0545Boundary of Binary TreePremium
0549Binary Tree Longest Consecutive Sequence IIPremium
0582Kill ProcessPremium
0663Equal Tree PartitionPremium
0666Path Sum IVPremium
0694Number of Distinct IslandsPremium
0737Sentence Similarity IIPremium
0742Closest Leaf in a Binary TreePremium
0785Is Graph Bipartite?
0797All Paths From Source to Target
0802Find Eventual Safe States
0814Binary Tree Pruning
0851Loud and Rich
0863All Nodes Distance K in Binary Tree
0865Smallest Subtree with all the Deepest Nodes
0886Possible Bipartition
0934Shortest Bridge
0947Most Stones Removed with Same Row or Column
0951Flip Equivalent Binary Trees
0959Regions Cut By Slashes
0971Flip Binary Tree To Match Preorder Traversal
0979Distribute Coins in Binary Tree
0988Smallest String Starting From Leaf
0990Satisfiability of Equality Equations
1020Number of Enclaves
1026Maximum Difference Between Node and Ancestor
1034Coloring A Border
1038Binary Search Tree to Greater Sum Tree
1042Flower Planting With No Adjacent
1059All Paths from Source Lead to DestinationPremium
1080Insufficient Nodes in Root to Leaf Paths
1102Path With Maximum Minimum ValuePremium
1110Delete Nodes And Return Forest
1120Maximum Average SubtreePremium
1123Lowest Common Ancestor of Deepest Leaves
1129Shortest Path with Alternating Colors
1135Connecting Cities With Minimum CostPremium
1136Parallel CoursesPremium
1145Binary Tree Coloring Game
1202Smallest String With Swaps
1214Two Sum BSTsPremium
1233Remove Sub-Folders from the Filesystem
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
1305All Elements in Two Binary Search Trees
1306Jump Game III
1311Get Watched Videos by Your Friends
1315Sum of Nodes with Even-Valued Grandparent
1319Number of Operations to Make Network Connected
1325Delete Leaves With a Given Value
1334Find the City With the Smallest Number of Neighbors at a Threshold Distance
1339Maximum Product of Splitted Binary Tree
1361Validate Binary Tree Nodes
1367Linked List in Binary Tree
1376Time Needed to Inform All Employees
1382Balance a Binary Search Tree
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
1506Find Root of N-Ary TreePremium
1514Path with Maximum Probability
1519Number of Nodes in the Sub-Tree With the Same Label
1522Diameter of N-Ary TreePremium
1530Number of Good Leaf Nodes Pairs
1557Minimum Number of Vertices to Reach All Nodes
1559Detect Cycles in 2D Grid
1600Throne Inheritance
1612Check If Two Expression Trees are EquivalentPremium
1615Maximal Network Rank
1625Lexicographically Smallest String After Applying Operations
1631Path With Minimum Effort
1644Lowest Common Ancestor of a Binary Tree IIPremium
1660Correct a Binary TreePremium
1666Change the Root of a Binary TreePremium
1676Lowest Common Ancestor of a Binary Tree IVPremium
1722Minimize Hamming Distance After Swap Operations
1740Find Distance in a Binary TreePremium
1743Restore the Array From Adjacent Pairs
1778Shortest Path in a Hidden GridPremium
1786Number of Restricted Paths From First to Last Node
1810Minimum Path Cost in a Hidden GridPremium
1820Maximum Number of Accepted InvitationsPremium
1858Longest Word With All PrefixesPremium
1905Count Sub Islands
1973Count Nodes Equal to Sum of DescendantsPremium
1976Number of Ways to Arrive at Destination
1992Find All Groups of Farmland
1993Operations on Tree
2039The Time When the Network Becomes Idle
2049Count Nodes With the Highest Score
2077Paths in Maze That Lead to Same RoomPremium
2093Minimum Cost to Reach City With DiscountsPremium
2096Step-By-Step Directions From a Binary Tree Node to Another
2101Detonate the Maximum Bombs
2115Find All Possible Recipes from Given Supplies
2192All Ancestors of a Node in a Directed Acyclic Graph
2265Count Nodes Equal to Average of Subtree
2285Maximum Total Importance of Roads
2297Jump Game VIIIPremium
2316Count Unreachable Pairs of Nodes in an Undirected Graph
2359Find Closest Node to Given Two Nodes
2368Reachable Nodes With Restrictions
2374Node With Highest Edge Score
2378Choose Edges to Maximize Score in a TreePremium
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
2473Minimum Cost to Buy ApplesPremium
2476Closest Nodes Queries in a Binary Search Tree
2477Minimum Fuel Cost to Report to the Capital
2492Minimum Score of a Path Between Two Cities
2497Maximum Star Sum of a Graph
2556Disconnect Path in a Binary Matrix by at Most One Flip
2596Check Knight Tour Configuration
2641Cousins in Binary Tree II
2658Maximum Number of Fish in a Grid
2662Minimum Cost of a Path With Special Roads
2685Count the Number of Complete Components
2737Find the Closest Marked NodePremium
2764Is Array a Preorder of Some ‌Binary TreePremium
2773Height of Special Binary TreePremium
2775Undefined to NullPremium
2852Sum of Remoteness of All CellsPremium
2924Find Champion II
2925Maximum Score After Applying Operations on a Tree
2976Minimum Cost to Convert String I

Hard (111)

Hard problems
No.Problem
0124Binary Tree Maximum Path Sum
0297Serialize and Deserialize Binary Tree
0329Longest Increasing Path in a Matrix
0332Reconstruct Itinerary
0472Concatenated Words
0514Freedom Trail
0685Redundant Connection II
0749Contain Virus
0778Swim in Rising Water
0269Alien DictionaryPremium
0272Closest Binary Search Tree Value IIPremium
0302Smallest Rectangle Enclosing Black PixelsPremium
0428Serialize and Deserialize N-ary TreePremium
0431Encode N-ary Tree to Binary TreePremium
0499The Maze IIIPremium
0631Design Excel Sum FormulaPremium
0642Design Search Autocomplete SystemPremium
0711Number of Distinct Islands IIPremium
0753Cracking the Safe
0765Couples Holding Hands
0827Making A Large Island
0834Sum of Distances in Tree
0839Similar String Groups
0847Shortest Path Visiting All Nodes
0882Reachable Nodes In Subdivided Graph
0913Cat and Mouse
0924Minimize Malware Spread
0928Minimize Malware Spread II
0968Binary Tree Cameras
0987Vertical Order Traversal of a Binary Tree
1028Recover a Tree From Preorder Traversal
1036Escape a Large Maze
1153String Transforms Into Another StringPremium
1168Optimize Water Distribution in a VillagePremium
1192Critical Connections in a Network
1203Sort Items by Groups Respecting Dependencies
1298Maximum Candies You Can Get from Boxes
1368Minimum Cost to Make at Least One Valid Path in a Grid
1373Maximum Sum BST in Binary Tree
1377Frog Position After T Seconds
1483Kth Ancestor of a Tree Node
1489Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
1494Parallel Courses II
1516Move Sub-Tree of N-Ary TreePremium
1548The Most Similar Path in a GraphPremium
1568Minimum Number of Days to Disconnect Island
1579Remove Max Number of Edges to Keep Graph Fully Traversable
1591Strange Printer II
1632Rank Transform of a Matrix
1697Checking Existence of Edge Length Limited Paths
1719Number Of Ways To Reconstruct A Tree
1724Checking Existence of Edge Length Limited Paths IIPremium
1728Cat and Mouse II
1761Minimum Degree of a Connected Trio in a Graph
1766Tree of Coprimes
1782Count Pairs Of Nodes
1857Largest Color Value in a Directed Graph
1916Count Ways to Build Rooms in an Ant Colony
1928Minimum Cost to Reach Destination in Time
1932Merge BSTs to Create Single BST
1938Maximum Genetic Difference Query
1970Last Day Where You Can Still Cross
2003Smallest Missing Genetic Value in Each Subtree
2045Second Minimum Time to Reach Destination
2050Parallel Courses III
2065Maximum Path Quality of a Graph
2076Process Restricted Friend Requests
2092Find All People With Secret
2097Valid Arrangement of Pairs
2123Minimum Operations to Remove Adjacent Ones in MatrixPremium
2127Maximum Employees to Be Invited to a Meeting
2203Minimum Weighted Subgraph With the Required Paths
2204Distance to a Cycle in Undirected GraphPremium
2242Maximum Score of a Node Sequence
2246Longest Path With Different Adjacent Characters
2247Maximum Cost of Trip With K HighwaysPremium
2277Closest Node to Path in TreePremium
2290Minimum Obstacle Removal to Reach Corner
2307Check for Contradictions in EquationsPremium
2313Minimum Flips in Binary Tree to Get ResultPremium
2322Minimum Score After Removals on a Tree
2328Number of Increasing Paths in a Grid
2360Longest Cycle in a Graph
2371Minimize Maximum Value in a GridPremium
2392Build a Matrix With Conditions
2421Number of Good Paths
2440Create Components With Same Value
2458Height of Binary Tree After Subtree Removal Queries
2479Maximum XOR of Two Non-Overlapping SubtreesPremium
2493Divide Nodes Into the Maximum Number of Groups
2508Add Edges to Make Degrees of All Nodes Even
2538Difference Between Maximum and Minimum Price Sum
2577Minimum Time to Visit a Cell In a Grid
2581Count Number of Possible Root Nodes
2603Collect Coins in a Tree
2608Shortest Cycle in a Graph
2642Design Graph With Shortest Path Calculator
2646Minimize the Total Price of the Trips
2699Modify Graph Edge Weights
2714Find Shortest Path with K HopsPremium
2791Count Paths That Can Form a Palindrome in a Tree
2792Count Nodes That Are Great EnoughPremium
2846Minimum Edge Weight Equilibrium Queries in a Tree
2858Minimum Edge Reversals So Every Node Is Reachable
2867Count Valid Paths in a Tree
2872Maximum Number of K-Divisible Components
2876Count Visited Nodes in a Directed Graph
2920Maximum Points After Collecting Coins From All Nodes
2959Number of Possible Sets of Closing Branches
2973Find Number of Coins to Place in Tree Nodes
2977Minimum Cost to Convert String II

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.