Depth-First Search
Depth-First Search Interview Questions: The Depth-First Search Pattern
Follow one path as far as it goes, then back up and try the next. On trees this gives the preorder, inorder and postorder traversals; on graphs it needs a visited set to avoid revisiting nodes. Below are the depth-first search interview questions from LeetCode, each with a step-by-step visual solution.
Interactive problems
Free to open
How do you recognise a depth-first search problem?
You need to explore every node, test whether a path exists, work with tree structure, or compute something that depends on a node's children before the node itself: the postorder shape behind most tree DP.
What is the time complexity of the depth-first search pattern?
O(V + E) time. Space is O(h) for the recursion stack, where h is depth, which is O(n) in the worst case for a skewed tree.
Depth-First Search interview questions: practice problems
Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.
- Introduction to DFSFree
- DFS FundamentalsFree
- Return Values in DFSPro
- Invert Binary TreePro
- Maximum Depth of Binary TreePro
- Same TreePro
- Leaf-Similar TreesPro
- Balanced Binary TreePro
- Subtree of Another TreePro
- Path SumPro
- Passing Values Down (State)Pro
- Validate Binary Search TreePro
- Kth Smallest Element in a BSTPro
- Delete Node in a BSTPro
- Search in a Binary Search TreePro
- Insert into a Binary Search TreePro
- Inorder Successor in BSTPro
- Largest BST SubtreePro
- Vertical Order Traversal of a Binary TreePro
- Recover Binary Search TreePro
- Construct Binary Search Tree from Preorder TraversalPro
- Construct Binary Tree from Preorder and Inorder TraversalPro
- Serialize and Deserialize Binary TreePro
- Binary Tree TiltPro
- Diameter of Binary TreePro
- Lowest Common Ancestor of a Binary TreePro
- Path Sum IIPro
- Path Sum IIIPro
- Longest ZigZag Path in a Binary TreePro
- Count Good Nodes in Binary TreePro
- Longest Univalue PathPro
- Graphs OverviewPro
- Graph Representation: Adjacency ListPro
- Clone GraphPro
- Graph Valid TreePro
- Matrices as GraphsPro
- Flood FillPro
- Types of DFS (Tree Traversals)Pro
- Binary Tree Inorder TraversalFree
- Two Sum IV - Input is a BSTFree
- Number of IslandsPro
- Making A Large IslandPro
- Number of Distinct IslandsPro
- Surrounded RegionsPro
- Pacific Atlantic Water FlowFree
- Longest Increasing Path in a MatrixPro
Depth-First Search problems by difficulty and complexity
The difficulty, running time and extra space of every depth-first search solution on this page, as each lesson derives them.
| Lesson | Difficulty | Best | Average | Worst | Space |
|---|---|---|---|---|---|
| Introduction to DFS | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| DFS Fundamentals | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Return Values in DFS | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Invert Binary Tree | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Maximum Depth of Binary Tree | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Same Tree | Easy | Ω(1) | Θ(n) | O(n) | O(h) |
| Leaf-Similar Trees | Easy | Ω(n + m) | Θ(n + m) | O(n + m) | O(n + m) |
| Balanced Binary Tree | Easy | Ω(1) | Θ(n) | O(n) | O(h) |
| Subtree of Another Tree | Easy | Ω(n) | Θ(m · n) | O(m · n) | O(h) |
| Path Sum | Easy | Ω(h) | Θ(n) | O(n) | O(h) |
| Passing Values Down (State) | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Validate Binary Search Tree | Medium | Ω(1) | Θ(n) | O(n) | O(h) |
| Kth Smallest Element in a BST | Medium | Ω(h + k) | Θ(h + k) | O(n) | O(h) |
| Delete Node in a BST | Medium | Ω(1) | Θ(log n) | O(h) | O(h) |
| Search in a Binary Search Tree | Easy | Ω(1) | Θ(log n) | O(n) | O(1) |
| Insert into a Binary Search Tree | Medium | Ω(1) | Θ(log n) | O(h) | O(1) |
| Inorder Successor in BST | Medium | Ω(1) | Θ(log n) | O(h) | O(1) |
| Largest BST Subtree | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Vertical Order Traversal of a Binary Tree | Hard | Ω(n log n) | Θ(n log n) | O(n log n) | O(n) |
| Recover Binary Search Tree | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Construct Binary Search Tree from Preorder Traversal | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Construct Binary Tree from Preorder and Inorder Traversal | Medium | Ω(n) | Θ(n) | O(n) | O(n) |
| Serialize and Deserialize Binary Tree | Hard | Ω(n) | Θ(n) | O(n) | O(n) |
| Binary Tree Tilt | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Diameter of Binary Tree | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Lowest Common Ancestor of a Binary Tree | Medium | Ω(1) | Θ(n) | O(n) | O(h) |
| Path Sum II | Medium | Ω(n) | Θ(n log n) | O(n²) | O(n) |
| Path Sum III | Medium | Ω(n) | Θ(n) | O(n) | O(n) |
| Longest ZigZag Path in a Binary Tree | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Count Good Nodes in Binary Tree | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Longest Univalue Path | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Graphs Overview | Medium | Ω(V + E) | Θ(V + E) | O(V + E) | O(V + E) |
| Graph Representation: Adjacency List | Medium | Ω(V + E) | Θ(V + E) | O(V + E) | O(V + E) |
| Clone Graph | Medium | Ω(V + E) | Θ(V + E) | O(V + E) | O(V) |
| Graph Valid Tree | Medium | Ω(V + E) | Θ(V + E) | O(V + E) | O(V + E) |
| Matrices as Graphs | Medium | Ω(1) | Θ(m·n) | O(m·n) | O(m·n) |
| Flood Fill | Easy | Ω(1) | Θ(m·n) | O(m·n) | O(m·n) |
| Types of DFS (Tree Traversals) | Medium | Ω(n) | Θ(n) | O(n) | O(h) |
| Binary Tree Inorder Traversal | Easy | Ω(n) | Θ(n) | O(n) | O(h) |
| Two Sum IV - Input is a BST | Easy | Ω(1) | Θ(n) | O(n) | O(n) |
| Number of Islands | Medium | Ω(m·n) | Θ(m·n) | O(m·n) | O(m·n) |
| Making A Large Island | Hard | Ω(R·C) | Θ(R·C) | O(R·C) | O(R·C) |
| Number of Distinct Islands | Medium | Ω(m · n) | Θ(m · n) | O(m · n) | O(m · n) |
| Surrounded Regions | Medium | Ω(m·n) | Θ(m·n) | O(m·n) | O(m·n) |
| Pacific Atlantic Water Flow | Medium | Ω(m·n) | Θ(m·n) | O(m·n) | O(m·n) |
| Longest Increasing Path in a Matrix | Hard | Ω(m · n) | Θ(m · n) | O(m · n) | O(m · n) |
Related patterns and concepts
The underlying technique is covered from first principles in the depth-first search lesson in the DSA visualizer curriculum. Depth-First Search is one of the 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.
Every other coding interview pattern
Two Pointers · 37 lessons
- Introduction to Two PointersFree
- Reverse String
- Reverse Vowels of a String
- Reverse Words in a String
- Two Sum II - Input Array Is SortedFree
- Max Number of K-Sum Pairs
- Valid Palindrome
- Merge Strings Alternately
- Greatest Common Divisor of Strings
- Merge Sorted Array
- Remove Duplicates from Sorted Array
- String Compression
- Remove Element
- Rotate Array
- Next Permutation
- Repeated String Match
- Find the Index of the First Occurrence in a StringFree
- Shortest Palindrome
- Squares of a Sorted Array
- Is Subsequence
- Valid Palindrome II
- Longest Palindromic Substring
- Palindromic Substrings
- Encode and Decode Strings
- Container With Most Water
- 3-Sum
- 3Sum Closest
- 4Sum
- Valid Triangle Number
- Move Zeroes
- Sort Colors
- Trapping Rain Water
- Multiply Strings
- String to Integer (atoi)
- Add Binary
- Add Strings
- Plus One
Hash Map · 20 lessons
- Two SumFree
- Contains Duplicate
- Find the Difference of Two Arrays
- Unique Number of Occurrences
- Valid Anagram
- Longest PalindromeFree
- Determine if Two Strings Are Close
- Equal Row and Column Pairs
- Group Anagrams
- Top K Frequent Elements
- Longest Consecutive Sequence
- Valid Sudoku
- Detect Squares
- Majority Element
- Majority Element II
- Isomorphic Strings
- Word Pattern
- Ransom Note
- First Unique Character in a String
- Roman to Integer
Sliding Window · 21 lessons
- Introduction to Sliding WindowFree
- Maximum Number of Vowels in a Substring of Given Length
- Longest Subarray of 1's After Deleting One Element
- Longest Substring Without Repeating CharactersFree
- Longest Repeating Character Replacement
- Minimum Window Substring
- Minimum Size Subarray Sum
- Max Consecutive Ones III
- Binary Subarrays With Sum
- Count Number of Nice Subarrays
- Number of Substrings Containing All Three Characters
- Fruit Into Baskets
- Longest Substring with At Most K Distinct Characters
- Number of Recent Calls
- Contains Duplicate II
- Fixed-Length Sliding Window
- Maximum Points You Can Obtain from Cards
- Maximum Sum of Distinct Subarrays With Length K
- Permutation in String
- Find All Anagrams in a String
- Sliding Window Maximum
Linked List · 23 lessons
- Linked List OverviewFree
- Reverse Linked ListFree
- Middle of the Linked ListFree
- Delete the Middle Node of a Linked List
- Odd Even Linked List
- Maximum Twin Sum of a Linked List
- Intersection of Two Linked ListsFree
- Merge Two Sorted ListsFree
- Add Two NumbersFree
- Linked List CycleFree
- Linked List Cycle IIFree
- Sort ListFree
- Rotate ListFree
- Palindrome Linked ListFree
- Remove Nth Node From End of ListFree
- Reorder ListFree
- Swap Nodes in PairsFree
- LRU CacheFree
- LFU Cache
- Find the Duplicate NumberFree
- Copy List with Random PointerFree
- Reverse Nodes in k-GroupFree
- Happy NumberFree
Stack · 24 lessons
- Stack OverviewFree
- Valid ParenthesesFree
- Decode String
- Longest Valid Parentheses
- Monotonic Stack Pattern
- Daily Temperatures
- Largest Rectangle in Histogram
- Maximal Rectangle
- Evaluate Reverse Polish Notation
- Min Stack
- Implement Queue using StacksFree
- Car Fleet
- Next Greater Element I
- Next Greater Element II
- Asteroid Collision
- Online Stock Span
- Sum of Subarray Minimums
- Sum of Subarray Ranges
- Remove K Digits
- Simplify Path
- Basic Calculator II
- Basic Calculator
- Removing Stars From a String
- Remove All Adjacent Duplicates in String
Binary Search · 20 lessons
- Binary SearchFree
- Search Insert Position
- First Bad Version
- Guess Number Higher or Lower
- Successful Pairs of Spells and Potions
- Search Suggestions System
- Single Element in a Sorted Array
- Sqrt(x)
- Valid Perfect Square
- Find Peak Element
- Find a Peak Element II
- Koko Eating Bananas (Apple Harvest)
- Split Array Largest Sum
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Search a 2D Matrix
- Search a 2D Matrix II
- Time Based Key-Value Store
- Median of Two Sorted Arrays
Heap / Priority Queue · 16 lessons
- Heap OverviewFree
- Kth Largest Element in an Array
- Smallest Number in Infinite Set
- Maximum Subsequence Score
- Total Cost to Hire K Workers
- Kth Largest Element in a StreamFree
- K Closest Points to Origin
- Find K Closest Elements
- Merge K Sorted Lists
- Design Twitter
- Kth Smallest Element in a Sorted Matrix
- Find Median from Data Stream
- Last Stone Weight
- Network Delay Time
- Min Cost to Connect All Points
- Swim in Rising Water
Breadth-First Search · 18 lessons
- Introduction to BFSFree
- BFS OverviewFree
- Maximum Level Sum of a Binary Tree
- Binary Tree Level Order Traversal
- Symmetric Tree
- Binary Tree Right Side View
- Binary Tree Zigzag Level Order Traversal
- Maximum Width of Binary Tree
- All Nodes Distance K in Binary Tree
- Graphs OverviewFree
- Minimum Knight Moves
- Rotting Oranges
- Nearest Exit from Entrance in Maze
- Walls and Gates
- 01 Matrix
- Bus Routes
- Word Ladder
- Cheapest Flights Within K Stops
Backtracking · 17 lessons
- Introduction to BacktrackingFree
- Solution Space Trees
- Subsets (Power Set)
- Permutations
- Permutations II
- Combinations
- Letter Case Permutation
- N-Queens
- Sudoku Solver
- Subsets II
- Combination Sum
- Combination Sum II
- Combination Sum III
- Generate Parentheses
- Word Search
- Letter Combinations of a Phone Number
- Palindrome Partitioning
Graphs (Topological Sort) · 16 lessons
- Ordering Dependencies (Topological Sort)Free
- Course Schedule
- Course Schedule II
- Minimum Height Trees
- Alien Dictionary
- Redundant Connection
- Accounts Merge
- Critical Connections in a Network
- Keys and Rooms
- Number of Provinces
- Reorder Routes to Make All Paths Lead to the City Zero
- Evaluate Division
- Is Graph Bipartite?
- Number of Operations to Make Network Connected
- Path With Minimum Effort
- Reconstruct Itinerary
Dynamic Programming · 41 lessons
- Intro to Dynamic ProgrammingFree
- Solving a Question with DPFree
- Fibonacci Number
- N-th Tribonacci Number
- Domino and Tromino Tiling
- Counting Bits
- Pascal's Triangle
- Min Cost Climbing Stairs
- House Robber
- House Robber II
- House Robber III
- Coin Change
- Coin Change II
- Maximum Product Subarray
- Combination Sum IV
- Partition Equal Subset Sum
- Last Stone Weight II
- Target Sum
- Decode Ways
- Maximal Square
- Unique Paths
- Unique Paths II
- Minimum Path Sum
- Triangle
- Longest Common Subsequence
- Longest Palindromic Subsequence
- Palindrome Partitioning II
- Edit Distance
- Interleaving String
- Distinct Subsequences
- Regular Expression Matching
- Wildcard Matching
- Burst Balloons
- Best Time to Buy and Sell Stock with Cooldown
- Best Time to Buy and Sell Stock with Transaction Fee
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Longest Increasing Subsequence
- Number of Longest Increasing Subsequence
- Word Break
- Maximum Profit in Job Scheduling
Greedy Algorithms · 17 lessons
- Introduction to Greedy AlgorithmsFree
- Kids With the Greatest Number of Candies
- Can Place Flowers
- Dota2 Senate
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Increasing Triplet Subsequence
- Gas Station
- Jump Game
- Jump Game II
- Task Scheduler
- Partition Labels
- Valid Parenthesis String
- Hand of Straights
- Merge Triplets to Form Target Triplet
- Integer to Roman
- Candy
