Pattern 16 of 22

Backtracking Pattern: Template + 105 LeetCode Problems

Build candidates one choice at a time and abandon a branch the moment it cannot work.

Easy
3
Medium
71
Hard
31

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.

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

Eyes only

Meet the backtracking 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 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)

Easy problems
No.Problem
0257Binary Tree Paths
0401Binary Watch
1863Sum of All Subset XOR Totals

Medium (71)

Medium problems
No.Problem
0017Letter Combinations of a Phone Number
0022Generate Parentheses
0039Combination Sum
0040Combination Sum II
0046Permutations
0047Permutations II
0077Combinations
0078Subsets
0079Word Search
0089Gray Code
0090Subsets II
0093Restore IP Addresses
0095Unique Binary Search Trees II
0113Path Sum II
0131Palindrome Partitioning
0216Combination Sum III
0306Additive Number
0357Count Numbers with Unique Digits
0473Matchsticks to Square
0491Non-decreasing Subsequences
0494Target Sum
0526Beautiful Arrangement
0638Shopping Offers
0698Partition to K Equal Sum Subsets
0254Factor CombinationsPremium
0267Palindrome Permutation IIPremium
0291Word Pattern IIPremium
0294Flip Game IIPremium
0320Generalized AbbreviationPremium
0351Android Unlock PatternsPremium
0681Next Closest TimePremium
0756Pyramid Transition Matrix
0784Letter Case Permutation
0797All Paths From Source to Target
0816Ambiguous Coordinates
0842Split Array into Fibonacci Sequence
0949Largest Time for Given Digits
0967Numbers With Same Consecutive Differences
0988Smallest String Starting From Leaf
1066Campus Bikes IIPremium
1079Letter Tile Possibilities
1087Brace ExpansionPremium
1215Stepping NumbersPremium
1219Path with Maximum Gold
1238Circular Permutation in Binary Representation
1239Maximum Length of a Concatenated String with Unique Characters
1258Synonymous SentencesPremium
1286Iterator for Combination
1415The k-th Lexicographical String of All Happy Strings of Length n
1593Split a String Into the Max Number of Unique Substrings
1718Construct the Lexicographically Largest Valid Sequence
1774Closest Dessert Cost
1849Splitting a String Into Descending Consecutive Values
1947Maximum Compatibility Score Sum
1980Find Unique Binary String
1986Minimum Number of Work Sessions to Finish the Tasks
2002Maximum Product of the Length of Two Palindromic Subsequences
2044Count Number of Maximum Bitwise-OR Subsets
2048Next Greater Numerically Balanced Number
2152Minimum Number of Lines to Cover PointsPremium
2178Maximum Split of Positive Even Integers
2212Maximum Points in an Archery Competition
2305Fair Distribution of Cookies
2375Construct Smallest Number From DI String
2397Maximum Rows Covered by Columns
2597The Number of Beautiful Subsets
2664The Knight’s TourPremium
2698Find the Punishment Number of an Integer
2708Maximum Strength of a Group
2767Partition String Into Minimum Beautiful Substrings
2992Number of Self-Divisible PermutationsPremium

Hard (31)

Hard problems
No.Problem
0037Sudoku Solver
0051N-Queens
0052N-Queens II
0126Word Ladder II
0140Word Break II
0212Word Search II
0282Expression Add Operators
0301Remove Invalid Parentheses
067924 Game
0691Stickers to Spell Word
0411Minimum Unique Word AbbreviationPremium
0425Word SquaresPremium
0465Optimal Account BalancingPremium
0489Robot Room CleanerPremium
0773Sliding Puzzle
0980Unique Paths III
0996Number of Squareful Arrays
1088Confusing Number IIPremium
1096Brace Expansion II
1240Tiling a Rectangle with the Fewest Squares
1255Maximum Score Words Formed by Letters
1307Verbal Arithmetic Puzzle
1467Probability of a Two Boxes Having The Same Number of Distinct Balls
1601Maximum Number of Achievable Transfer Requests
1655Distribute Repeating Integers
1723Find Minimum Time to Finish All Jobs
1799Maximize Score After N Operations
2014Longest Subsequence Repeated k Times
2056Number of Valid Move Combinations On Chessboard
2065Maximum Path Quality of a Graph
2151Maximum Good People Based on Statements

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.