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.

Backtracking — Python template
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 result

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

Related LeetCode topics

Easy (3)

#ProblemDifficultyTopics
257Binary Tree PathsEasyTree, Depth-First Search, String +2
401Binary WatchEasyBit Manipulation, Backtracking
1863Sum of All Subset XOR TotalsEasyBit Manipulation, Array, Math +3

Medium (71)

#ProblemDifficultyTopics
17Letter Combinations of a Phone NumberMediumHash Table, String, Backtracking
22Generate ParenthesesMediumString, Dynamic Programming, Backtracking
39Combination SumMediumArray, Backtracking
40Combination Sum IIMediumArray, Backtracking
46PermutationsMediumArray, Backtracking
47Permutations IIMediumArray, Backtracking, Sorting
77CombinationsMediumBacktracking
78SubsetsMediumBit Manipulation, Array, Backtracking
79Word SearchMediumDepth-First Search, Array, String +2
89Gray CodeMediumBit Manipulation, Math, Backtracking
90Subsets IIMediumBit Manipulation, Array, Backtracking
93Restore IP AddressesMediumString, Backtracking
95Unique Binary Search Trees IIMediumTree, Binary Search Tree, Dynamic Programming +2
113Path Sum IIMediumTree, Depth-First Search, Backtracking +1
131Palindrome PartitioningMediumString, Dynamic Programming, Backtracking
216Combination Sum IIIMediumArray, Backtracking
306Additive NumberMediumString, Backtracking
357Count Numbers with Unique DigitsMediumMath, Dynamic Programming, Backtracking
473Matchsticks to SquareMediumBit Manipulation, Array, Dynamic Programming +2
491Non-decreasing SubsequencesMediumBit Manipulation, Array, Hash Table +1
494Target SumMediumArray, Dynamic Programming, Backtracking
526Beautiful ArrangementMediumBit Manipulation, Array, Dynamic Programming +2
638Shopping OffersMediumBit Manipulation, Memoization, Array +3
698Partition to K Equal Sum SubsetsMediumBit Manipulation, Memoization, Array +3
254Factor CombinationsPremiumMediumBacktracking
267Palindrome Permutation IIPremiumMediumHash Table, String, Backtracking
291Word Pattern IIPremiumMediumHash Table, String, Backtracking
294Flip Game IIPremiumMediumMemoization, Math, Dynamic Programming +2
320Generalized AbbreviationPremiumMediumBit Manipulation, String, Backtracking
351Android Unlock PatternsPremiumMediumBit Manipulation, Dynamic Programming, Backtracking +1
681Next Closest TimePremiumMediumHash Table, String, Backtracking +1
756Pyramid Transition MatrixMediumBit Manipulation, Hash Table, String +1
784Letter Case PermutationMediumBit Manipulation, String, Backtracking
797All Paths From Source to TargetMediumDepth-First Search, Breadth-First Search, Graph +1
816Ambiguous CoordinatesMediumString, Backtracking, Enumeration
842Split Array into Fibonacci SequenceMediumString, Backtracking
949Largest Time for Given DigitsMediumArray, String, Backtracking +1
967Numbers With Same Consecutive DifferencesMediumBreadth-First Search, Backtracking
988Smallest String Starting From LeafMediumTree, Depth-First Search, String +2
1066Campus Bikes IIPremiumMediumBit Manipulation, Array, Dynamic Programming +2
1079Letter Tile PossibilitiesMediumHash Table, String, Backtracking +1
1087Brace ExpansionPremiumMediumStack, Breadth-First Search, String +2
1215Stepping NumbersPremiumMediumBreadth-First Search, Math, Backtracking
1219Path with Maximum GoldMediumArray, Backtracking, Matrix
1238Circular Permutation in Binary RepresentationMediumBit Manipulation, Math, Backtracking
1239Maximum Length of a Concatenated String with Unique CharactersMediumBit Manipulation, Array, String +1
1258Synonymous SentencesPremiumMediumSort, Union Find, Array +3
1286Iterator for CombinationMediumDesign, String, Backtracking +1
1415The k-th Lexicographical String of All Happy Strings of Length nMediumString, Backtracking
1593Split a String Into the Max Number of Unique SubstringsMediumHash Table, String, Backtracking
1718Construct the Lexicographically Largest Valid SequenceMediumArray, Backtracking
1774Closest Dessert CostMediumArray, Dynamic Programming, Backtracking
1849Splitting a String Into Descending Consecutive ValuesMediumString, Backtracking, Enumeration
1947Maximum Compatibility Score SumMediumBit Manipulation, Array, Dynamic Programming +2
1980Find Unique Binary StringMediumArray, Hash Table, String +1
1986Minimum Number of Work Sessions to Finish the TasksMediumBit Manipulation, Array, Dynamic Programming +2
2002Maximum Product of the Length of Two Palindromic SubsequencesMediumBit Manipulation, String, Dynamic Programming +2
2044Count Number of Maximum Bitwise-OR SubsetsMediumBit Manipulation, Array, Backtracking +1
2048Next Greater Numerically Balanced NumberMediumHash Table, Math, Backtracking +2
2152Minimum Number of Lines to Cover PointsPremiumMediumBit Manipulation, Geometry, Array +5
2178Maximum Split of Positive Even IntegersMediumGreedy, Math, Backtracking
2212Maximum Points in an Archery CompetitionMediumBit Manipulation, Array, Backtracking +1
2305Fair Distribution of CookiesMediumBit Manipulation, Array, Dynamic Programming +2
2375Construct Smallest Number From DI StringMediumStack, Greedy, String +1
2397Maximum Rows Covered by ColumnsMediumBit Manipulation, Array, Backtracking +2
2597The Number of Beautiful SubsetsMediumArray, Hash Table, Math +4
2664The Knight’s TourPremiumMediumArray, Backtracking, Matrix
2698Find the Punishment Number of an IntegerMediumMath, Backtracking
2708Maximum Strength of a GroupMediumGreedy, Bit Manipulation, Array +4
2767Partition String Into Minimum Beautiful SubstringsMediumHash Table, String, Dynamic Programming +1
2992Number of Self-Divisible PermutationsPremiumMediumBit Manipulation, Array, Math +4

Hard (31)

#ProblemDifficultyTopics
37Sudoku SolverHardArray, Hash Table, Backtracking +1
51N-QueensHardArray, Backtracking
52N-Queens IIHardBacktracking
126Word Ladder IIHardBreadth-First Search, Hash Table, String +1
140Word Break IIHardTrie, Memoization, Array +4
212Word Search IIHardTrie, Array, String +2
282Expression Add OperatorsHardMath, String, Backtracking
301Remove Invalid ParenthesesHardBreadth-First Search, String, Backtracking
67924 GameHardArray, Math, Backtracking
691Stickers to Spell WordHardBit Manipulation, Memoization, Array +5
411Minimum Unique Word AbbreviationPremiumHardBit Manipulation, Array, String +1
425Word SquaresPremiumHardTrie, Array, String +1
465Optimal Account BalancingPremiumHardBit Manipulation, Array, Dynamic Programming +2
489Robot Room CleanerPremiumHardBacktracking, Interactive
773Sliding PuzzleHardBreadth-First Search, Memoization, Array +3
980Unique Paths IIIHardBit Manipulation, Array, Backtracking +1
996Number of Squareful ArraysHardBit Manipulation, Array, Hash Table +4
1088Confusing Number IIPremiumHardMath, Backtracking
1096Brace Expansion IIHardStack, Breadth-First Search, Hash Table +3
1240Tiling a Rectangle with the Fewest SquaresHardBacktracking
1255Maximum Score Words Formed by LettersHardBit Manipulation, Array, Hash Table +5
1307Verbal Arithmetic PuzzleHardArray, Math, String +1
1467Probability of a Two Boxes Having The Same Number of Distinct BallsHardArray, Math, Dynamic Programming +3
1601Maximum Number of Achievable Transfer RequestsHardBit Manipulation, Array, Backtracking +1
1655Distribute Repeating IntegersHardBit Manipulation, Array, Dynamic Programming +2
1723Find Minimum Time to Finish All JobsHardBit Manipulation, Array, Dynamic Programming +2
1799Maximize Score After N OperationsHardBit Manipulation, Array, Math +4
2014Longest Subsequence Repeated k TimesHardGreedy, String, Backtracking +2
2056Number of Valid Move Combinations On ChessboardHardArray, String, Backtracking +1
2065Maximum Path Quality of a GraphHardGraph, Array, Backtracking
2151Maximum Good People Based on StatementsHardBit 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.