Backtracking Pattern: Template + 105 LeetCode Problems
Build candidates one choice at a time and abandon a branch the moment it cannot work.
- 3 Easy
- 71 Medium
- 31 Hard
- Exponential — O(n·2ⁿ) for subsets, O(n·n!) for permutations time
What the backtracking pattern is
Backtracking is depth-first search over the tree of partial solutions, with one discipline attached: every choice made on the way down is undone on the way back up, so a single mutable path can stand in for the whole tree instead of copying state at every node. The template is always the same three lines — choose, recurse, un-choose — and the two decisions that make a problem specific are what the recursion index means and where the pruning goes. Pruning is what separates a working answer from a timing out one: rejecting a branch at depth two skips every leaf beneath it, so a check placed before the recursive call is worth far more than the same check at the leaf. The one thing to be deliberate about is the copy: appending the live path to the result list stores a reference that later mutations will corrupt, so the copy has to be taken when the answer is recorded.
When to use it
- The problem asks for all subsets, permutations, combinations, partitions or paths — the arrangements themselves, not a count.
- A valid answer is built incrementally and partial answers can be judged invalid early.
- The constraints are small — n around 20 or less — because the search is exponential by nature.
- You are placing things under conflict rules: queens, sudoku digits, word squares.
The backtracking 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 105 problems listed below.
def subsets(nums):
result, path = [], []
def explore(start):
result.append(path[:]) # copy: path keeps mutating after this
for i in range(start, len(nums)):
path.append(nums[i]) # choose
explore(i + 1) # explore what is left
path.pop() # un-choose, restoring the caller's state
explore(0)
return resultComplexity characteristics
- Time
- Exponential — O(n·2ⁿ) for subsets, O(n·n!) for permutations
- Auxiliary space
- O(n), plus the output
The search tree has one leaf per candidate answer, so the running time is the number of answers times the cost of recording each one. There is no polynomial version, which is why the constraints on these problems are small. Pruning does not change the worst case but changes the observed time enormously, because rejecting a branch at depth two removes every leaf beneath it. The working space is the recursion depth and the single mutable path; the result list is output, not working memory.
All 105 backtracking LeetCode problems
Every problem in the library the backtracking pattern applies to, grouped by LeetCode's own difficulty rating. 86 of the 105 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 (3)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 257 | Binary Tree Paths | Easy | Tree, Depth-First Search, String +2 |
| 401 | Binary Watch | Easy | Bit Manipulation, Backtracking |
| 1863 | Sum of All Subset XOR Totals | Easy | Bit Manipulation, Array, Math +3 |
Medium (71)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 17 | Letter Combinations of a Phone Number | Medium | Hash Table, String, Backtracking |
| 22 | Generate Parentheses | Medium | String, Dynamic Programming, Backtracking |
| 39 | Combination Sum | Medium | Array, Backtracking |
| 40 | Combination Sum II | Medium | Array, Backtracking |
| 46 | Permutations | Medium | Array, Backtracking |
| 47 | Permutations II | Medium | Array, Backtracking, Sorting |
| 77 | Combinations | Medium | Backtracking |
| 78 | Subsets | Medium | Bit Manipulation, Array, Backtracking |
| 79 | Word Search | Medium | Depth-First Search, Array, String +2 |
| 89 | Gray Code | Medium | Bit Manipulation, Math, Backtracking |
| 90 | Subsets II | Medium | Bit Manipulation, Array, Backtracking |
| 93 | Restore IP Addresses | Medium | String, Backtracking |
| 95 | Unique Binary Search Trees II | Medium | Tree, Binary Search Tree, Dynamic Programming +2 |
| 113 | Path Sum II | Medium | Tree, Depth-First Search, Backtracking +1 |
| 131 | Palindrome Partitioning | Medium | String, Dynamic Programming, Backtracking |
| 216 | Combination Sum III | Medium | Array, Backtracking |
| 306 | Additive Number | Medium | String, Backtracking |
| 357 | Count Numbers with Unique Digits | Medium | Math, Dynamic Programming, Backtracking |
| 473 | Matchsticks to Square | Medium | Bit Manipulation, Array, Dynamic Programming +2 |
| 491 | Non-decreasing Subsequences | Medium | Bit Manipulation, Array, Hash Table +1 |
| 494 | Target Sum | Medium | Array, Dynamic Programming, Backtracking |
| 526 | Beautiful Arrangement | Medium | Bit Manipulation, Array, Dynamic Programming +2 |
| 638 | Shopping Offers | Medium | Bit Manipulation, Memoization, Array +3 |
| 698 | Partition to K Equal Sum Subsets | Medium | Bit Manipulation, Memoization, Array +3 |
| 254 | Factor CombinationsPremium | Medium | Backtracking |
| 267 | Palindrome Permutation IIPremium | Medium | Hash Table, String, Backtracking |
| 291 | Word Pattern IIPremium | Medium | Hash Table, String, Backtracking |
| 294 | Flip Game IIPremium | Medium | Memoization, Math, Dynamic Programming +2 |
| 320 | Generalized AbbreviationPremium | Medium | Bit Manipulation, String, Backtracking |
| 351 | Android Unlock PatternsPremium | Medium | Bit Manipulation, Dynamic Programming, Backtracking +1 |
| 681 | Next Closest TimePremium | Medium | Hash Table, String, Backtracking +1 |
| 756 | Pyramid Transition Matrix | Medium | Bit Manipulation, Hash Table, String +1 |
| 784 | Letter Case Permutation | Medium | Bit Manipulation, String, Backtracking |
| 797 | All Paths From Source to Target | Medium | Depth-First Search, Breadth-First Search, Graph +1 |
| 816 | Ambiguous Coordinates | Medium | String, Backtracking, Enumeration |
| 842 | Split Array into Fibonacci Sequence | Medium | String, Backtracking |
| 949 | Largest Time for Given Digits | Medium | Array, String, Backtracking +1 |
| 967 | Numbers With Same Consecutive Differences | Medium | Breadth-First Search, Backtracking |
| 988 | Smallest String Starting From Leaf | Medium | Tree, Depth-First Search, String +2 |
| 1066 | Campus Bikes IIPremium | Medium | Bit Manipulation, Array, Dynamic Programming +2 |
| 1079 | Letter Tile Possibilities | Medium | Hash Table, String, Backtracking +1 |
| 1087 | Brace ExpansionPremium | Medium | Stack, Breadth-First Search, String +2 |
| 1215 | Stepping NumbersPremium | Medium | Breadth-First Search, Math, Backtracking |
| 1219 | Path with Maximum Gold | Medium | Array, Backtracking, Matrix |
| 1238 | Circular Permutation in Binary Representation | Medium | Bit Manipulation, Math, Backtracking |
| 1239 | Maximum Length of a Concatenated String with Unique Characters | Medium | Bit Manipulation, Array, String +1 |
| 1258 | Synonymous SentencesPremium | Medium | Sort, Union Find, Array +3 |
| 1286 | Iterator for Combination | Medium | Design, String, Backtracking +1 |
| 1415 | The k-th Lexicographical String of All Happy Strings of Length n | Medium | String, Backtracking |
| 1593 | Split a String Into the Max Number of Unique Substrings | Medium | Hash Table, String, Backtracking |
| 1718 | Construct the Lexicographically Largest Valid Sequence | Medium | Array, Backtracking |
| 1774 | Closest Dessert Cost | Medium | Array, Dynamic Programming, Backtracking |
| 1849 | Splitting a String Into Descending Consecutive Values | Medium | String, Backtracking, Enumeration |
| 1947 | Maximum Compatibility Score Sum | Medium | Bit Manipulation, Array, Dynamic Programming +2 |
| 1980 | Find Unique Binary String | Medium | Array, Hash Table, String +1 |
| 1986 | Minimum Number of Work Sessions to Finish the Tasks | Medium | Bit Manipulation, Array, Dynamic Programming +2 |
| 2002 | Maximum Product of the Length of Two Palindromic Subsequences | Medium | Bit Manipulation, String, Dynamic Programming +2 |
| 2044 | Count Number of Maximum Bitwise-OR Subsets | Medium | Bit Manipulation, Array, Backtracking +1 |
| 2048 | Next Greater Numerically Balanced Number | Medium | Hash Table, Math, Backtracking +2 |
| 2152 | Minimum Number of Lines to Cover PointsPremium | Medium | Bit Manipulation, Geometry, Array +5 |
| 2178 | Maximum Split of Positive Even Integers | Medium | Greedy, Math, Backtracking |
| 2212 | Maximum Points in an Archery Competition | Medium | Bit Manipulation, Array, Backtracking +1 |
| 2305 | Fair Distribution of Cookies | Medium | Bit Manipulation, Array, Dynamic Programming +2 |
| 2375 | Construct Smallest Number From DI String | Medium | Stack, Greedy, String +1 |
| 2397 | Maximum Rows Covered by Columns | Medium | Bit Manipulation, Array, Backtracking +2 |
| 2597 | The Number of Beautiful Subsets | Medium | Array, Hash Table, Math +4 |
| 2664 | The Knight’s TourPremium | Medium | Array, Backtracking, Matrix |
| 2698 | Find the Punishment Number of an Integer | Medium | Math, Backtracking |
| 2708 | Maximum Strength of a Group | Medium | Greedy, Bit Manipulation, Array +4 |
| 2767 | Partition String Into Minimum Beautiful Substrings | Medium | Hash Table, String, Dynamic Programming +1 |
| 2992 | Number of Self-Divisible PermutationsPremium | Medium | Bit Manipulation, Array, Math +4 |
Hard (31)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 37 | Sudoku Solver | Hard | Array, Hash Table, Backtracking +1 |
| 51 | N-Queens | Hard | Array, Backtracking |
| 52 | N-Queens II | Hard | Backtracking |
| 126 | Word Ladder II | Hard | Breadth-First Search, Hash Table, String +1 |
| 140 | Word Break II | Hard | Trie, Memoization, Array +4 |
| 212 | Word Search II | Hard | Trie, Array, String +2 |
| 282 | Expression Add Operators | Hard | Math, String, Backtracking |
| 301 | Remove Invalid Parentheses | Hard | Breadth-First Search, String, Backtracking |
| 679 | 24 Game | Hard | Array, Math, Backtracking |
| 691 | Stickers to Spell Word | Hard | Bit Manipulation, Memoization, Array +5 |
| 411 | Minimum Unique Word AbbreviationPremium | Hard | Bit Manipulation, Array, String +1 |
| 425 | Word SquaresPremium | Hard | Trie, Array, String +1 |
| 465 | Optimal Account BalancingPremium | Hard | Bit Manipulation, Array, Dynamic Programming +2 |
| 489 | Robot Room CleanerPremium | Hard | Backtracking, Interactive |
| 773 | Sliding Puzzle | Hard | Breadth-First Search, Memoization, Array +3 |
| 980 | Unique Paths III | Hard | Bit Manipulation, Array, Backtracking +1 |
| 996 | Number of Squareful Arrays | Hard | Bit Manipulation, Array, Hash Table +4 |
| 1088 | Confusing Number IIPremium | Hard | Math, Backtracking |
| 1096 | Brace Expansion II | Hard | Stack, Breadth-First Search, Hash Table +3 |
| 1240 | Tiling a Rectangle with the Fewest Squares | Hard | Backtracking |
| 1255 | Maximum Score Words Formed by Letters | Hard | Bit Manipulation, Array, Hash Table +5 |
| 1307 | Verbal Arithmetic Puzzle | Hard | Array, Math, String +1 |
| 1467 | Probability of a Two Boxes Having The Same Number of Distinct Balls | Hard | Array, Math, Dynamic Programming +3 |
| 1601 | Maximum Number of Achievable Transfer Requests | Hard | Bit Manipulation, Array, Backtracking +1 |
| 1655 | Distribute Repeating Integers | Hard | Bit Manipulation, Array, Dynamic Programming +2 |
| 1723 | Find Minimum Time to Finish All Jobs | Hard | Bit Manipulation, Array, Dynamic Programming +2 |
| 1799 | Maximize Score After N Operations | Hard | Bit Manipulation, Array, Math +4 |
| 2014 | Longest Subsequence Repeated k Times | Hard | Greedy, String, Backtracking +2 |
| 2056 | Number of Valid Move Combinations On Chessboard | Hard | Array, String, Backtracking +1 |
| 2065 | Maximum Path Quality of a Graph | Hard | Graph, Array, Backtracking |
| 2151 | Maximum Good People Based on Statements | Hard | Bit Manipulation, Array, Backtracking +1 |
Related patterns
Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.
Backtracking pattern FAQ
What is the backtracking pattern?
Backtracking is depth-first search over the tree of partial solutions, with one discipline attached: every choice made on the way down is undone on the way back up, so a single mutable path can stand in for the whole tree instead of copying state at every node.
How many LeetCode problems use the backtracking pattern?
This page lists 105 LeetCode problems that the backtracking pattern applies to: 3 Easy, 71 Medium and 31 Hard. 86 of them carry a complete Python solution with complexity analysis.
What is the time complexity of the backtracking pattern?
Exponential — O(n·2ⁿ) for subsets, O(n·n!) for permutations time and O(n), plus the output space. The search tree has one leaf per candidate answer, so the running time is the number of answers times the cost of recording each one. There is no polynomial version, which is why the constraints on these problems are small. Pruning does not change the worst case but changes the observed time enormously, because rejecting a branch at depth two removes every leaf beneath it. The working space is the recursion depth and the single mutable path; the result list is output, not working memory.
When should I use the backtracking pattern in an interview?
The problem asks for all subsets, permutations, combinations, partitions or paths — the arrangements themselves, not a count. A valid answer is built incrementally and partial answers can be judged invalid early.
Which backtracking problem should I start with?
LeetCode 257. Binary Tree Paths 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 backtracking?
Depth-First Search, Dynamic Programming, Bit Manipulation, Trie. 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 backtracking 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.