Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Backtracking & Recursion

Backtracking

exponential

Choose → recurse → un-choose. Prune as early as the constraints allow to cut the search tree.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstSubsets / Permutations / Combinations
0%
mastery
0/14 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

"Find all valid ...", "is there a way to ...": N-Queens, Sudoku, word search, string partitions, valid parentheses, with early-checkable rules.

  1. 1Brute force

    Generate every full candidate, then test validity.

  2. 2The observation

    Building invalid completions: early constraint checks cut whole subtrees.

  3. 3Why it works

    The current partial assignment always satisfies every constraint checked so far; choose, recurse, un-choose keeps one path in memory.

Reach for it when

  • +Build a configuration incrementally with constraints you can check early — board placement, partitions, valid strings.
  • +'Find all valid …', 'is there a way to …', or 'solve this puzzle' (Sudoku, N-Queens, word search).
  • +The search space is exponential but pruning cuts most of it.

Not when

  • ×Only a count or optimum is needed and subproblems overlapuse Memoise it: DP
  • ×The used-set state repeats across pathsuse Memoise on the mask: bitmask DP
  • ×A provable greedy or formula existsuse Greedy; don't explore a tree you don't need
  • ×Huge state space, weak pruning, and you need one answer fastuse BFS or heuristics

Intuition

Backtracking is subsets/permutations with a conscience: you build a candidate step by step, but the moment it can't possibly lead to a valid answer, you abandon that branch and rewind. It's how you solve a maze — walk forward, hit a wall, back up to the last fork, try another door.

Read the full intuition

It's the same "choose → recurse → un-choose" loop as enumeration, plus a third ingredient: a validity / pruning check before (or right after) you make a move. Good pruning is the whole game — N-Queens has 64-choose-8 raw placements, but checking "is this square attacked?" before placing chops the tree by orders of magnitude.

The reusable frame:

  1. Base case — path is a complete solution → record it.
  2. For each candidate move:
    • if it's invalid, skip (prune).
    • else place it, recurse, then remove it (backtrack).

Worked tiny example — Generate Parentheses, n=2. State = (open used, close used). You may add '(' while open<n, and ')' only while close<open (else it's unbalanced — pruned). That single close<open rule prevents every invalid string from ever being built.

Key idea

The skill to drill: spotting the earliest point you can prove a branch is dead. The earlier you prune, the faster everything runs.

Why it costs what it costs

Time exponential (problem-specific). worst case explores the whole decision tree; pruning cuts it dramatically but the bound stays exponential (e.g. roughly O(n!) for N-Queens).

Space O(depth). recursion stack plus the partial solution, both bounded by the solution length.

Practice

Next · Foundation

Generate Parentheses

Only add ')' when close < open: invalid branches never start.

0/14 solved
  • Generate ParenthesesFoundationFoundationAmazon, MetaMedium
  • Combination Sum IIApply it · Each element once with duplicates in input.Apply itAmazon, UberMedium
  • Palindrome PartitioningOne change · Choose cut positions.One changeAmazon, UberMedium
  • Restore IP AddressesOne change · Segment rules (0-255, no leading zeros).One changeMicrosoft, AdobeMedium
  • Word SearchTwists · State is a grid path; must undo visited marks.TwistsMeta, AmazonMedium
  • N-QueensBranches · Global constraints (columns, diagonals).BranchesAmazon, GoogleHard
  • Word Search IICombine · Many words at once.CombineAmazon, GoogleHard
  • Sudoku SolverMastery checkMastery checkGoogle, UberHard
  • Chessboard and QueensCSESMedium
  • Grid Path DescriptionCSESHard
  • Filling TrominosCSESHard
  • Good Permutations with Alternating ParityAtlassianOAEasy
  • Word Break IIHard
  • Matchsticks to SquareMedium

Pitfalls

Classic bugs

  • !Weak or late pruning makes the tree explode: check validity before placing, at the earliest provable dead end.
  • !Forgot to undo a change (unmark cell, pop choice): sibling branches see corrupted state.
  • !Grid search: mark visited before recursing and restore after. Miss either and you loop or block paths.
  • !Saved the live mutable path at the base case: append a copy. But copy only at leaves, not at every node.
  • !N-Queens diagonals: r-c (offset it, can be negative) and r+c are the two diagonals; mixing them up is classic.

Looks like it, isn't

  • Word Ladder needs Graph BFS / DFS
    Why
    Shortest transformation sequence is BFS on an implicit graph.
  • Word Break needs 1D / Fibonacci-style
    Why
    Backtracking repeats suffixes; dp over prefix positions. source ↗
  • Palindrome Partitioning II needs Palindromic Substrings
    Why
    Only the minimum cut is needed: palindrome table + 1D cut DP.
  • Tallest Billboard needs 0/1 Knapsack
    Why
    3n assignments collapse into dp[difference] = best shorter-side height (the editorial also shows meet-in-the-middle). source ↗
Go deepervariants and techniques · 2 combinations · interviewer follow-ups · resources

Variants and techniques

  • Divide and Conquer (merge-sort counting)Split the array in half, solve each half, then count/merge cross pairs in linear time while merging sorted halves.
  • Constraint placementPlace items honoring constraints, track conflicts in sets/arrays. N-Queens, Sudoku Solver.
  • Grid path searchDFS 4-directionally, mark visited, restore on exit. Word Search.
  • PartitioningCut the input into pieces, recurse on the remainder, validate each piece. Palindrome Partitioning.
  • Balanced constructionBuild a string/sequence honoring a running invariant (e.g. close<open). Generate Parentheses.

Combinations

  • Trie (Prefix Tree)+Backtracking

    find all dictionary words in a grid

    Trie (Prefix Tree):
    prefix pruning for all words at once
    Backtracking:
    grid path enumeration with undo

    Word Search II

  • Backtracking+Bit Tricks & Bitmasking

    N-Queens, Sudoku, placement puzzles

    Backtracking:
    the search
    Bit Tricks & Bitmasking:
    O(1) constraint sets as bitmasks

    N-QueensSudoku SolverChessboard and Queens

Follow-ups interviewers ask

  1. 01Just the count of solutions, not all of them? → often a DP exists (overlapping subproblems) — far faster than enumerating.
  2. 02How do you prune earlier? → tighten the validity check (constraint propagation, sorted input + skip duplicates).
  3. 03Memory for huge output? → yield/stream solutions instead of materialising the whole list.
  4. 04Can it be parallelised? → independent subtrees from the first choice can run concurrently.

State table

depth choice path valid? action
0 place '(' ( open<2 ✓ recurse
1 place '(' (( open=2 ✓ recurse
2 place ')' (() close<open ✓ recurse
3 place ')' (()) len=4 ✓ record, backtrack

Resources

  • Complete Search with RecursionUSACO Guide · course
  • Recursion I explore cardLeetCode · course
  • Recursion cheatsheetTech Interview Handbook · article
  • General approach to backtracking questionsLeetCode discuss · article
  • Competitive Programmer's HandbookAntti Laaksonen · book
Subsets / Permutations / CombinationsTree BFS (Level Order)
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial