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.

Depth-First Search — Python 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.

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)

#ProblemDifficultyTopics
94Binary Tree Inorder TraversalEasyStack, Tree, Depth-First Search +1
100Same TreeEasyTree, Depth-First Search, Breadth-First Search +1
101Symmetric TreeEasyTree, Depth-First Search, Breadth-First Search +1
104Maximum Depth of Binary TreeEasyTree, Depth-First Search, Breadth-First Search +1
110Balanced Binary TreeEasyTree, Depth-First Search, Binary Tree
111Minimum Depth of Binary TreeEasyTree, Depth-First Search, Breadth-First Search +1
112Path SumEasyTree, Depth-First Search, Breadth-First Search +1
144Binary Tree Preorder TraversalEasyStack, Tree, Depth-First Search +1
145Binary Tree Postorder TraversalEasyStack, Tree, Depth-First Search +1
226Invert Binary TreeEasyTree, Depth-First Search, Breadth-First Search +1
257Binary Tree PathsEasyTree, Depth-First Search, String +2
404Sum of Left LeavesEasyTree, Depth-First Search, Breadth-First Search +1
463Island PerimeterEasyDepth-First Search, Breadth-First Search, Array +1
501Find Mode in Binary Search TreeEasyTree, Depth-First Search, Binary Search Tree +1
530Minimum Absolute Difference in BSTEasyTree, Depth-First Search, Breadth-First Search +2
543Diameter of Binary TreeEasyTree, Depth-First Search, Binary Tree
559Maximum Depth of N-ary TreeEasyTree, Depth-First Search, Breadth-First Search
563Binary Tree TiltEasyTree, Depth-First Search, Binary Tree
572Subtree of Another TreeEasyTree, Depth-First Search, Binary Tree +2
589N-ary Tree Preorder TraversalEasyStack, Tree, Depth-First Search
590N-ary Tree Postorder TraversalEasyStack, Tree, Depth-First Search
617Merge Two Binary TreesEasyTree, Depth-First Search, Breadth-First Search +1
637Average of Levels in Binary TreeEasyTree, Depth-First Search, Breadth-First Search +1
653Two Sum IV - Input is a BSTEasyTree, Depth-First Search, Breadth-First Search +4
671Second Minimum Node In a Binary TreeEasyTree, Depth-First Search, Binary Tree
733Flood FillEasyDepth-First Search, Breadth-First Search, Array +1
872Leaf-Similar TreesEasyTree, Depth-First Search, Binary Tree
270Closest Binary Search Tree ValuePremiumEasyTree, Depth-First Search, Binary Search Tree +2
783Minimum Distance Between BST NodesEasyTree, Depth-First Search, Breadth-First Search +2
897Increasing Order Search TreeEasyStack, Tree, Depth-First Search +2
938Range Sum of BSTEasyTree, Depth-First Search, Binary Search Tree +1
965Univalued Binary TreeEasyTree, Depth-First Search, Breadth-First Search +1
993Cousins in Binary TreeEasyTree, Depth-First Search, Breadth-First Search +1
997Find the Town JudgeEasyGraph, Array, Hash Table
1022Sum of Root To Leaf Binary NumbersEasyTree, Depth-First Search, Binary Tree
1379Find a Corresponding Node of a Binary Tree in a Clone of That TreeEasyTree, Depth-First Search, Breadth-First Search +1
1469Find All The Lonely NodesPremiumEasyTree, Depth-First Search, Breadth-First Search +1
1791Find Center of Star GraphEasyGraph
1971Find if Path Exists in GraphEasyDepth-First Search, Breadth-First Search, Union Find +1
2331Evaluate Boolean Binary TreeEasyTree, Depth-First Search, Binary Tree
2689Extract Kth Character From The Rope TreePremiumEasyTree, Depth-First Search, Binary Tree

Medium (214)

#ProblemDifficultyTopics
79Word SearchMediumDepth-First Search, Array, String +2
98Validate Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +1
99Recover Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +1
113Path Sum IIMediumTree, Depth-First Search, Backtracking +1
114Flatten Binary Tree to Linked ListMediumStack, Tree, Depth-First Search +2
116Populating Next Right Pointers in Each NodeMediumTree, Depth-First Search, Breadth-First Search +2
117Populating Next Right Pointers in Each Node IIMediumTree, Depth-First Search, Breadth-First Search +2
129Sum Root to Leaf NumbersMediumTree, Depth-First Search, Binary Tree
130Surrounded RegionsMediumDepth-First Search, Breadth-First Search, Union Find +2
133Clone GraphMediumDepth-First Search, Breadth-First Search, Graph +1
199Binary Tree Right Side ViewMediumTree, Depth-First Search, Breadth-First Search +1
200Number of IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
207Course ScheduleMediumDepth-First Search, Breadth-First Search, Graph +1
210Course Schedule IIMediumDepth-First Search, Breadth-First Search, Graph +1
211Design Add and Search Words Data StructureMediumDepth-First Search, Design, Trie +1
230Kth Smallest Element in a BSTMediumTree, Depth-First Search, Binary Search Tree +1
235Lowest Common Ancestor of a Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +1
236Lowest Common Ancestor of a Binary TreeMediumTree, Depth-First Search, Binary Tree
310Minimum Height TreesMediumDepth-First Search, Breadth-First Search, Graph +1
337House Robber IIIMediumTree, Depth-First Search, Dynamic Programming +1
341Flatten Nested List IteratorMediumStack, Tree, Depth-First Search +3
365Water and Jug ProblemMediumDepth-First Search, Breadth-First Search, Math
385Mini ParserMediumStack, Depth-First Search, String
386Lexicographical NumbersMediumDepth-First Search, Trie
388Longest Absolute File PathMediumStack, Depth-First Search, String
399Evaluate DivisionMediumDepth-First Search, Breadth-First Search, Union Find +4
417Pacific Atlantic Water FlowMediumDepth-First Search, Breadth-First Search, Array +1
419Battleships in a BoardMediumDepth-First Search, Array, Matrix
430Flatten a Multilevel Doubly Linked ListMediumDepth-First Search, Linked List, Doubly-Linked List
437Path Sum IIIMediumTree, Depth-First Search, Binary Tree
449Serialize and Deserialize BSTMediumTree, Depth-First Search, Breadth-First Search +4
508Most Frequent Subtree SumMediumTree, Depth-First Search, Hash Table +1
513Find Bottom Left Tree ValueMediumTree, Depth-First Search, Breadth-First Search +1
515Find Largest Value in Each Tree RowMediumTree, Depth-First Search, Breadth-First Search +1
529MinesweeperMediumDepth-First Search, Breadth-First Search, Array +1
538Convert BST to Greater TreeMediumTree, Depth-First Search, Binary Search Tree +1
547Number of ProvincesMediumDepth-First Search, Breadth-First Search, Union Find +1
565Array NestingMediumDepth-First Search, Array
606Construct String from Binary TreeMediumTree, Depth-First Search, String +1
623Add One Row to TreeMediumTree, Depth-First Search, Breadth-First Search +1
652Find Duplicate SubtreesMediumTree, Depth-First Search, Hash Table +1
655Print Binary TreeMediumTree, Depth-First Search, Breadth-First Search +1
662Maximum Width of Binary TreeMediumTree, Depth-First Search, Breadth-First Search +1
669Trim a Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +1
672Bulb Switcher IIMediumBit Manipulation, Depth-First Search, Breadth-First Search +1
676Implement Magic DictionaryMediumDepth-First Search, Design, Trie +2
684Redundant ConnectionMediumDepth-First Search, Breadth-First Search, Union Find +1
687Longest Univalue PathMediumTree, Depth-First Search, Binary Tree
690Employee ImportanceMediumTree, Depth-First Search, Breadth-First Search +2
695Max Area of IslandMediumDepth-First Search, Breadth-First Search, Union Find +2
721Accounts MergeMediumDepth-First Search, Breadth-First Search, Union Find +4
743Network Delay TimeMediumDepth-First Search, Breadth-First Search, Graph +2
787Cheapest Flights Within K StopsMediumDepth-First Search, Breadth-First Search, Graph +3
841Keys and RoomsMediumDepth-First Search, Breadth-First Search, Graph
1161Maximum Level Sum of a Binary TreeMediumTree, Depth-First Search, Breadth-First Search +1
1372Longest ZigZag Path in a Binary TreeMediumTree, Depth-First Search, Dynamic Programming +1
1448Count Good Nodes in Binary TreeMediumTree, Depth-First Search, Breadth-First Search +1
1466Reorder Routes to Make All Paths Lead to the City ZeroMediumDepth-First Search, Breadth-First Search, Graph
1584Min Cost to Connect All PointsMediumUnion Find, Graph, Array +1
156Binary Tree Upside DownPremiumMediumTree, Depth-First Search, Binary Tree
250Count Univalue SubtreesPremiumMediumTree, Depth-First Search, Binary Tree
261Graph Valid TreePremiumMediumDepth-First Search, Breadth-First Search, Union Find +1
277Find the CelebrityPremiumMediumGraph, Two Pointers, Interactive
285Inorder Successor in BSTPremiumMediumTree, Depth-First Search, Binary Search Tree +1
298Binary Tree Longest Consecutive SequencePremiumMediumTree, Depth-First Search, Binary Tree
314Binary Tree Vertical Order TraversalPremiumMediumTree, Depth-First Search, Breadth-First Search +3
323Number of Connected Components in an Undirected GraphPremiumMediumDepth-First Search, Breadth-First Search, Union Find +1
333Largest BST SubtreePremiumMediumTree, Depth-First Search, Binary Search Tree +2
339Nested List Weight SumPremiumMediumDepth-First Search, Breadth-First Search
364Nested List Weight Sum IIPremiumMediumStack, Depth-First Search, Breadth-First Search
366Find Leaves of Binary TreePremiumMediumTree, Depth-First Search, Binary Tree
426Convert Binary Search Tree to Sorted Doubly Linked ListPremiumMediumStack, Tree, Depth-First Search +4
444Sequence ReconstructionPremiumMediumGraph, Topological Sort, Array
490The MazePremiumMediumDepth-First Search, Breadth-First Search, Array +1
505The Maze IIPremiumMediumDepth-First Search, Breadth-First Search, Graph +4
536Construct Binary Tree from StringPremiumMediumStack, Tree, Depth-First Search +2
545Boundary of Binary TreePremiumMediumTree, Depth-First Search, Binary Tree
549Binary Tree Longest Consecutive Sequence IIPremiumMediumTree, Depth-First Search, Binary Tree
582Kill ProcessPremiumMediumTree, Depth-First Search, Breadth-First Search +2
663Equal Tree PartitionPremiumMediumTree, Depth-First Search, Binary Tree
666Path Sum IVPremiumMediumTree, Depth-First Search, Array +2
694Number of Distinct IslandsPremiumMediumDepth-First Search, Breadth-First Search, Union Find +2
737Sentence Similarity IIPremiumMediumDepth-First Search, Breadth-First Search, Union Find +3
742Closest Leaf in a Binary TreePremiumMediumTree, Depth-First Search, Breadth-First Search +1
785Is Graph Bipartite?MediumDepth-First Search, Breadth-First Search, Union Find +1
797All Paths From Source to TargetMediumDepth-First Search, Breadth-First Search, Graph +1
802Find Eventual Safe StatesMediumDepth-First Search, Breadth-First Search, Graph +1
814Binary Tree PruningMediumTree, Depth-First Search, Binary Tree
851Loud and RichMediumDepth-First Search, Graph, Topological Sort +1
863All Nodes Distance K in Binary TreeMediumTree, Depth-First Search, Breadth-First Search +2
865Smallest Subtree with all the Deepest NodesMediumTree, Depth-First Search, Breadth-First Search +2
886Possible BipartitionMediumDepth-First Search, Breadth-First Search, Union Find +1
934Shortest BridgeMediumDepth-First Search, Breadth-First Search, Array +1
947Most Stones Removed with Same Row or ColumnMediumDepth-First Search, Union Find, Graph +1
951Flip Equivalent Binary TreesMediumTree, Depth-First Search, Binary Tree
959Regions Cut By SlashesMediumDepth-First Search, Breadth-First Search, Union Find +3
971Flip Binary Tree To Match Preorder TraversalMediumTree, Depth-First Search, Binary Tree
979Distribute Coins in Binary TreeMediumTree, Depth-First Search, Binary Tree
988Smallest String Starting From LeafMediumTree, Depth-First Search, String +2
990Satisfiability of Equality EquationsMediumUnion Find, Graph, Array +1
1020Number of EnclavesMediumDepth-First Search, Breadth-First Search, Union Find +2
1026Maximum Difference Between Node and AncestorMediumTree, Depth-First Search, Binary Tree
1034Coloring A BorderMediumDepth-First Search, Breadth-First Search, Array +1
1038Binary Search Tree to Greater Sum TreeMediumTree, Depth-First Search, Binary Search Tree +1
1042Flower Planting With No AdjacentMediumDepth-First Search, Breadth-First Search, Graph
1059All Paths from Source Lead to DestinationPremiumMediumGraph, Topological Sort
1080Insufficient Nodes in Root to Leaf PathsMediumTree, Depth-First Search, Binary Tree
1102Path With Maximum Minimum ValuePremiumMediumDepth-First Search, Breadth-First Search, Union Find +4
1110Delete Nodes And Return ForestMediumTree, Depth-First Search, Array +2
1120Maximum Average SubtreePremiumMediumTree, Depth-First Search, Binary Tree
1123Lowest Common Ancestor of Deepest LeavesMediumTree, Depth-First Search, Breadth-First Search +2
1129Shortest Path with Alternating ColorsMediumBreadth-First Search, Graph
1135Connecting Cities With Minimum CostPremiumMediumUnion Find, Graph, Minimum Spanning Tree +1
1136Parallel CoursesPremiumMediumGraph, Topological Sort
1145Binary Tree Coloring GameMediumTree, Depth-First Search, Binary Tree
1202Smallest String With SwapsMediumDepth-First Search, Breadth-First Search, Union Find +4
1214Two Sum BSTsPremiumMediumStack, Tree, Depth-First Search +4
1233Remove Sub-Folders from the FilesystemMediumDepth-First Search, Trie, Array +1
1236Web CrawlerPremiumMediumDepth-First Search, Breadth-First Search, String +1
1242Web Crawler MultithreadedPremiumMediumDepth-First Search, Breadth-First Search, Concurrency
1245Tree DiameterPremiumMediumTree, Depth-First Search, Breadth-First Search +2
1254Number of Closed IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
1257Smallest Common RegionPremiumMediumTree, Depth-First Search, Breadth-First Search +3
1261Find Elements in a Contaminated Binary TreeMediumTree, Depth-First Search, Breadth-First Search +3
1267Count Servers that CommunicateMediumDepth-First Search, Breadth-First Search, Union Find +3
1273Delete Tree NodesPremiumMediumTree, Depth-First Search, Breadth-First Search +1
1302Deepest Leaves SumMediumTree, Depth-First Search, Breadth-First Search +1
1305All Elements in Two Binary Search TreesMediumTree, Depth-First Search, Binary Search Tree +2
1306Jump Game IIIMediumDepth-First Search, Breadth-First Search, Array
1311Get Watched Videos by Your FriendsMediumBreadth-First Search, Graph, Array +2
1315Sum of Nodes with Even-Valued GrandparentMediumTree, Depth-First Search, Breadth-First Search +1
1319Number of Operations to Make Network ConnectedMediumDepth-First Search, Breadth-First Search, Union Find +1
1325Delete Leaves With a Given ValueMediumTree, Depth-First Search, Binary Tree
1334Find the City With the Smallest Number of Neighbors at a Threshold DistanceMediumGraph, Dynamic Programming, Shortest Path
1339Maximum Product of Splitted Binary TreeMediumTree, Depth-First Search, Binary Tree
1361Validate Binary Tree NodesMediumTree, Depth-First Search, Breadth-First Search +3
1367Linked List in Binary TreeMediumTree, Depth-First Search, Linked List +1
1376Time Needed to Inform All EmployeesMediumTree, Depth-First Search, Breadth-First Search
1382Balance a Binary Search TreeMediumGreedy, Tree, Depth-First Search +3
1391Check if There is a Valid Path in a GridMediumDepth-First Search, Breadth-First Search, Union Find +2
1430Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary TreePremiumMediumTree, Depth-First Search, Breadth-First Search +1
1443Minimum Time to Collect All Apples in a TreeMediumTree, Depth-First Search, Breadth-First Search +1
1457Pseudo-Palindromic Paths in a Binary TreeMediumBit Manipulation, Tree, Depth-First Search +2
1462Course Schedule IVMediumDepth-First Search, Breadth-First Search, Graph +1
1485Clone Binary Tree With Random PointerPremiumMediumTree, Depth-First Search, Breadth-First Search +2
1490Clone N-ary TreePremiumMediumTree, Depth-First Search, Breadth-First Search +1
1506Find Root of N-Ary TreePremiumMediumBit Manipulation, Tree, Depth-First Search +1
1514Path with Maximum ProbabilityMediumGraph, Array, Shortest Path +1
1519Number of Nodes in the Sub-Tree With the Same LabelMediumTree, Depth-First Search, Breadth-First Search +2
1522Diameter of N-Ary TreePremiumMediumTree, Depth-First Search
1530Number of Good Leaf Nodes PairsMediumTree, Depth-First Search, Binary Tree
1557Minimum Number of Vertices to Reach All NodesMediumGraph
1559Detect Cycles in 2D GridMediumDepth-First Search, Breadth-First Search, Union Find +2
1600Throne InheritanceMediumTree, Depth-First Search, Design +1
1612Check If Two Expression Trees are EquivalentPremiumMediumTree, Depth-First Search, Hash Table +2
1615Maximal Network RankMediumGraph
1625Lexicographically Smallest String After Applying OperationsMediumDepth-First Search, Breadth-First Search, String +1
1631Path With Minimum EffortMediumDepth-First Search, Breadth-First Search, Union Find +4
1644Lowest Common Ancestor of a Binary Tree IIPremiumMediumTree, Depth-First Search, Binary Tree
1660Correct a Binary TreePremiumMediumTree, Depth-First Search, Breadth-First Search +2
1666Change the Root of a Binary TreePremiumMediumTree, Depth-First Search, Binary Tree
1676Lowest Common Ancestor of a Binary Tree IVPremiumMediumTree, Depth-First Search, Hash Table +1
1722Minimize Hamming Distance After Swap OperationsMediumDepth-First Search, Union Find, Array
1740Find Distance in a Binary TreePremiumMediumTree, Depth-First Search, Breadth-First Search +2
1743Restore the Array From Adjacent PairsMediumDepth-First Search, Array, Hash Table
1778Shortest Path in a Hidden GridPremiumMediumDepth-First Search, Breadth-First Search, Array +2
1786Number of Restricted Paths From First to Last NodeMediumGraph, Topological Sort, Dynamic Programming +2
1810Minimum Path Cost in a Hidden GridPremiumMediumDepth-First Search, Breadth-First Search, Graph +5
1820Maximum Number of Accepted InvitationsPremiumMediumDepth-First Search, Graph, Array +1
1858Longest Word With All PrefixesPremiumMediumDepth-First Search, Trie, Array +1
1905Count Sub IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
1973Count Nodes Equal to Sum of DescendantsPremiumMediumTree, Depth-First Search, Binary Tree
1976Number of Ways to Arrive at DestinationMediumGraph, Topological Sort, Dynamic Programming +1
1992Find All Groups of FarmlandMediumDepth-First Search, Breadth-First Search, Array +1
1993Operations on TreeMediumTree, Depth-First Search, Breadth-First Search +3
2039The Time When the Network Becomes IdleMediumBreadth-First Search, Graph, Array
2049Count Nodes With the Highest ScoreMediumTree, Depth-First Search, Array +1
2077Paths in Maze That Lead to Same RoomPremiumMediumGraph
2093Minimum Cost to Reach City With DiscountsPremiumMediumGraph, Shortest Path, Heap (Priority Queue)
2096Step-By-Step Directions From a Binary Tree Node to AnotherMediumTree, Depth-First Search, String +1
2101Detonate the Maximum BombsMediumDepth-First Search, Breadth-First Search, Graph +3
2115Find All Possible Recipes from Given SuppliesMediumGraph, Topological Sort, Array +2
2192All Ancestors of a Node in a Directed Acyclic GraphMediumDepth-First Search, Breadth-First Search, Graph +1
2265Count Nodes Equal to Average of SubtreeMediumTree, Depth-First Search, Binary Tree
2285Maximum Total Importance of RoadsMediumGreedy, Graph, Sorting +1
2297Jump Game VIIIPremiumMediumStack, Graph, Array +3
2316Count Unreachable Pairs of Nodes in an Undirected GraphMediumDepth-First Search, Breadth-First Search, Union Find +1
2359Find Closest Node to Given Two NodesMediumDepth-First Search, Graph
2368Reachable Nodes With RestrictionsMediumTree, Depth-First Search, Breadth-First Search +4
2374Node With Highest Edge ScoreMediumGraph, Hash Table
2378Choose Edges to Maximize Score in a TreePremiumMediumTree, Depth-First Search, Dynamic Programming
2385Amount of Time for Binary Tree to Be InfectedMediumTree, Depth-First Search, Breadth-First Search +2
2415Reverse Odd Levels of Binary TreeMediumTree, Depth-First Search, Breadth-First Search +1
2445Number of Nodes With Value OnePremiumMediumTree, Depth-First Search, Breadth-First Search +2
2467Most Profitable Path in a TreeMediumTree, Depth-First Search, Breadth-First Search +2
2473Minimum Cost to Buy ApplesPremiumMediumGraph, Array, Shortest Path +1
2476Closest Nodes Queries in a Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +3
2477Minimum Fuel Cost to Report to the CapitalMediumTree, Depth-First Search, Breadth-First Search +1
2492Minimum Score of a Path Between Two CitiesMediumDepth-First Search, Breadth-First Search, Union Find +1
2497Maximum Star Sum of a GraphMediumGreedy, Graph, Array +2
2556Disconnect Path in a Binary Matrix by at Most One FlipMediumDepth-First Search, Breadth-First Search, Array +2
2596Check Knight Tour ConfigurationMediumDepth-First Search, Breadth-First Search, Array +2
2641Cousins in Binary Tree IIMediumTree, Depth-First Search, Breadth-First Search +2
2658Maximum Number of Fish in a GridMediumDepth-First Search, Breadth-First Search, Union Find +2
2662Minimum Cost of a Path With Special RoadsMediumGraph, Array, Shortest Path +1
2685Count the Number of Complete ComponentsMediumDepth-First Search, Breadth-First Search, Union Find +1
2737Find the Closest Marked NodePremiumMediumGraph, Array, Shortest Path +1
2764Is Array a Preorder of Some ‌Binary TreePremiumMediumStack, Tree, Depth-First Search +1
2773Height of Special Binary TreePremiumMediumTree, Depth-First Search, Breadth-First Search +1
2775Undefined to NullPremiumMediumJavaScript
2852Sum of Remoteness of All CellsPremiumMediumDepth-First Search, Breadth-First Search, Union Find +3
2924Find Champion IIMediumGraph
2925Maximum Score After Applying Operations on a TreeMediumTree, Depth-First Search, Dynamic Programming
2976Minimum Cost to Convert String IMediumGraph, Array, String +1

Hard (111)

#ProblemDifficultyTopics
124Binary Tree Maximum Path SumHardTree, Depth-First Search, Dynamic Programming +1
297Serialize and Deserialize Binary TreeHardTree, Depth-First Search, Breadth-First Search +3
329Longest Increasing Path in a MatrixHardDepth-First Search, Breadth-First Search, Graph +5
332Reconstruct ItineraryHardDepth-First Search, Graph, Eulerian Circuit
472Concatenated WordsHardDepth-First Search, Trie, Array +3
514Freedom TrailHardDepth-First Search, Breadth-First Search, String +1
685Redundant Connection IIHardDepth-First Search, Breadth-First Search, Union Find +1
749Contain VirusHardDepth-First Search, Breadth-First Search, Array +2
778Swim in Rising WaterHardDepth-First Search, Breadth-First Search, Union Find +4
269Alien DictionaryPremiumHardDepth-First Search, Breadth-First Search, Graph +3
272Closest Binary Search Tree Value IIPremiumHardStack, Tree, Depth-First Search +4
302Smallest Rectangle Enclosing Black PixelsPremiumHardDepth-First Search, Breadth-First Search, Array +2
428Serialize and Deserialize N-ary TreePremiumHardTree, Depth-First Search, Breadth-First Search +1
431Encode N-ary Tree to Binary TreePremiumHardTree, Depth-First Search, Breadth-First Search +2
499The Maze IIIPremiumHardDepth-First Search, Breadth-First Search, Graph +5
631Design Excel Sum FormulaPremiumHardGraph, Design, Topological Sort +4
642Design Search Autocomplete SystemPremiumHardDepth-First Search, Design, Trie +4
711Number of Distinct Islands IIPremiumHardDepth-First Search, Breadth-First Search, Union Find +2
753Cracking the SafeHardDepth-First Search, Graph, Eulerian Circuit
765Couples Holding HandsHardGreedy, Depth-First Search, Breadth-First Search +2
827Making A Large IslandHardDepth-First Search, Breadth-First Search, Union Find +2
834Sum of Distances in TreeHardTree, Depth-First Search, Graph +1
839Similar String GroupsHardDepth-First Search, Breadth-First Search, Union Find +3
847Shortest Path Visiting All NodesHardBit Manipulation, Breadth-First Search, Graph +2
882Reachable Nodes In Subdivided GraphHardGraph, Shortest Path, Heap (Priority Queue)
913Cat and MouseHardGraph, Topological Sort, Memoization +3
924Minimize Malware SpreadHardDepth-First Search, Breadth-First Search, Union Find +3
928Minimize Malware Spread IIHardDepth-First Search, Breadth-First Search, Union Find +3
968Binary Tree CamerasHardTree, Depth-First Search, Dynamic Programming +1
987Vertical Order Traversal of a Binary TreeHardTree, Depth-First Search, Breadth-First Search +3
1028Recover a Tree From Preorder TraversalHardTree, Depth-First Search, String +1
1036Escape a Large MazeHardDepth-First Search, Breadth-First Search, Array +1
1153String Transforms Into Another StringPremiumHardGraph, Hash Table, String
1168Optimize Water Distribution in a VillagePremiumHardUnion Find, Graph, Minimum Spanning Tree +1
1192Critical Connections in a NetworkHardDepth-First Search, Graph, Biconnected Component
1203Sort Items by Groups Respecting DependenciesHardDepth-First Search, Breadth-First Search, Graph +1
1298Maximum Candies You Can Get from BoxesHardBreadth-First Search, Graph, Array
1368Minimum Cost to Make at Least One Valid Path in a GridHardBreadth-First Search, Graph, Array +3
1373Maximum Sum BST in Binary TreeHardTree, Depth-First Search, Binary Search Tree +2
1377Frog Position After T SecondsHardTree, Depth-First Search, Breadth-First Search +1
1483Kth Ancestor of a Tree NodeHardBit Manipulation, Tree, Depth-First Search +4
1489Find Critical and Pseudo-Critical Edges in Minimum Spanning TreeHardUnion Find, Graph, Minimum Spanning Tree +2
1494Parallel Courses IIHardBit Manipulation, Graph, Dynamic Programming +1
1516Move Sub-Tree of N-Ary TreePremiumHardTree, Depth-First Search
1548The Most Similar Path in a GraphPremiumHardGraph, Dynamic Programming
1568Minimum Number of Days to Disconnect IslandHardDepth-First Search, Breadth-First Search, Array +2
1579Remove Max Number of Edges to Keep Graph Fully TraversableHardUnion Find, Graph
1591Strange Printer IIHardGraph, Topological Sort, Array +1
1632Rank Transform of a MatrixHardUnion Find, Graph, Topological Sort +3
1697Checking Existence of Edge Length Limited PathsHardUnion Find, Graph, Array +2
1719Number Of Ways To Reconstruct A TreeHardTree, Graph
1724Checking Existence of Edge Length Limited Paths IIPremiumHardUnion Find, Graph, Minimum Spanning Tree
1728Cat and Mouse IIHardGraph, Topological Sort, Memoization +5
1761Minimum Degree of a Connected Trio in a GraphHardGraph, Enumeration
1766Tree of CoprimesHardTree, Depth-First Search, Array +2
1782Count Pairs Of NodesHardGraph, Array, Hash Table +4
1857Largest Color Value in a Directed GraphHardGraph, Topological Sort, Memoization +3
1916Count Ways to Build Rooms in an Ant ColonyHardTree, Graph, Topological Sort +3
1928Minimum Cost to Reach Destination in TimeHardGraph, Array, Dynamic Programming
1932Merge BSTs to Create Single BSTHardTree, Depth-First Search, Hash Table +2
1938Maximum Genetic Difference QueryHardBit Manipulation, Depth-First Search, Trie +2
1970Last Day Where You Can Still CrossHardDepth-First Search, Breadth-First Search, Union Find +3
2003Smallest Missing Genetic Value in Each SubtreeHardTree, Depth-First Search, Union Find +1
2045Second Minimum Time to Reach DestinationHardBreadth-First Search, Graph, Shortest Path
2050Parallel Courses IIIHardGraph, Topological Sort, Array +1
2065Maximum Path Quality of a GraphHardGraph, Array, Backtracking
2076Process Restricted Friend RequestsHardUnion Find, Graph
2092Find All People With SecretHardDepth-First Search, Breadth-First Search, Union Find +2
2097Valid Arrangement of PairsHardDepth-First Search, Graph, Eulerian Circuit
2123Minimum Operations to Remove Adjacent Ones in MatrixPremiumHardGraph, Array, Matrix
2127Maximum Employees to Be Invited to a MeetingHardDepth-First Search, Graph, Topological Sort
2203Minimum Weighted Subgraph With the Required PathsHardGraph, Shortest Path
2204Distance to a Cycle in Undirected GraphPremiumHardDepth-First Search, Breadth-First Search, Union Find +1
2242Maximum Score of a Node SequenceHardGraph, Array, Enumeration +1
2246Longest Path With Different Adjacent CharactersHardTree, Depth-First Search, Graph +3
2247Maximum Cost of Trip With K HighwaysPremiumHardBit Manipulation, Graph, Dynamic Programming +1
2277Closest Node to Path in TreePremiumHardTree, Depth-First Search, Breadth-First Search +1
2290Minimum Obstacle Removal to Reach CornerHardBreadth-First Search, Graph, Array +3
2307Check for Contradictions in EquationsPremiumHardDepth-First Search, Union Find, Graph +1
2313Minimum Flips in Binary Tree to Get ResultPremiumHardTree, Depth-First Search, Dynamic Programming +1
2322Minimum Score After Removals on a TreeHardBit Manipulation, Tree, Depth-First Search +1
2328Number of Increasing Paths in a GridHardDepth-First Search, Breadth-First Search, Graph +5
2360Longest Cycle in a GraphHardDepth-First Search, Breadth-First Search, Graph +1
2371Minimize Maximum Value in a GridPremiumHardUnion Find, Graph, Topological Sort +3
2392Build a Matrix With ConditionsHardGraph, Topological Sort, Array +1
2421Number of Good PathsHardTree, Union Find, Graph +3
2440Create Components With Same ValueHardTree, Depth-First Search, Array +2
2458Height of Binary Tree After Subtree Removal QueriesHardTree, Depth-First Search, Breadth-First Search +2
2479Maximum XOR of Two Non-Overlapping SubtreesPremiumHardTree, Depth-First Search, Graph +1
2493Divide Nodes Into the Maximum Number of GroupsHardDepth-First Search, Breadth-First Search, Union Find +1
2508Add Edges to Make Degrees of All Nodes EvenHardGraph, Hash Table
2538Difference Between Maximum and Minimum Price SumHardTree, Depth-First Search, Array +1
2577Minimum Time to Visit a Cell In a GridHardBreadth-First Search, Graph, Array +3
2581Count Number of Possible Root NodesHardTree, Depth-First Search, Array +2
2603Collect Coins in a TreeHardTree, Graph, Topological Sort +1
2608Shortest Cycle in a GraphHardBreadth-First Search, Graph
2642Design Graph With Shortest Path CalculatorHardGraph, Design, Shortest Path +1
2646Minimize the Total Price of the TripsHardTree, Depth-First Search, Graph +2
2699Modify Graph Edge WeightsHardGraph, Shortest Path, Heap (Priority Queue)
2714Find Shortest Path with K HopsPremiumHardGraph, Shortest Path, Heap (Priority Queue)
2791Count Paths That Can Form a Palindrome in a TreeHardBit Manipulation, Tree, Depth-First Search +2
2792Count Nodes That Are Great EnoughPremiumHardTree, Depth-First Search, Divide and Conquer +1
2846Minimum Edge Weight Equilibrium Queries in a TreeHardTree, Graph, Array +1
2858Minimum Edge Reversals So Every Node Is ReachableHardDepth-First Search, Breadth-First Search, Graph +1
2867Count Valid Paths in a TreeHardTree, Depth-First Search, Math +2
2872Maximum Number of K-Divisible ComponentsHardTree, Depth-First Search
2876Count Visited Nodes in a Directed GraphHardGraph, Memoization, Dynamic Programming
2920Maximum Points After Collecting Coins From All NodesHardBit Manipulation, Tree, Depth-First Search +3
2959Number of Possible Sets of Closing BranchesHardBit Manipulation, Graph, Enumeration +2
2973Find Number of Coins to Place in Tree NodesHardTree, Depth-First Search, Dynamic Programming +2
2977Minimum Cost to Convert String IIHardGraph, 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.