Bitpath

Recursion & Backtracking

Learn to read the call stack, trust the smaller call, and tame branching recursion with memory. Then use recursion as a tree of choices: subsets, permutations, and backtracking searches that give up on dead ends early.

  • Beginner
  • 4 units, 12 lessons, 144 exercises
  • Python, JavaScript or TypeScript
  • Builds on Algorithm Foundations

Unit 01 · 3 lessons

Functions that call themselves

Read and write simple recursion without fear

  1. > start01The base case
  2. 02The call stack
  3. BOSSShrink the problem
Unit prize
  1. 01
    The base case

    Every recursion needs a way to stop

  2. 02
    The call stack

    Where unfinished calls wait

  3. BOSS
    Shrink the problem

    Trust the smaller call, then make it fast

Read the unit guide

A recursive function solves a problem by handing a smaller version of the same problem to itself. It needs two parts. The base case answers the smallest input directly. The recursive case does one small piece of work and calls the function on an input that is closer to the base case.

Every call must move toward the base case, and the base case must be reachable. If a step can jump over it (counting down by 2 past an n == 0 check) or never changes the input, the calls never stop.

Each call gets its own frame on the call stack: its own copy of the parameters and a note of where to continue. A frame waits while the call it made runs. The last call made is the first to finish, so code written before the recursive call runs on the way down and code after it runs on the way back up.

Depth costs memory. Recursion that goes n calls deep holds n frames at once, which is O(n) space even with no lists in sight. Python gives up at about 1,000 frames by default (RecursionError); JavaScript engines stop at roughly ten thousand (RangeError).

To write recursion, trust the smaller call. Assume the function already works for a smaller input, then ask what single step turns that answer into yours: add the first number, append the first character, multiply once more.

How fast the input shrinks decides the cost. Shrinking by 1 gives n calls. Halving gives about log₂ n calls, which is how fast power computes b¹⁰⁰⁰ in 11 calls instead of 1,000.

Unit 02 · 3 lessons

Branching recursion

See why two recursive calls explode, and how memory tames them

  1. 01Two calls, one tree
  2. 02Remember answers
  3. BOSSDivide and conquer
Unit prize
  1. 01
    Two calls, one tree

    Why branching recursion grows so fast

  2. 02
    Remember answers

    Memoization turns a tree back into a chain

  3. BOSS
    Divide and conquer

    Split in half, and throw a half away when you can

Read the unit guide

One recursive call per call makes a chain: n calls for an input of n. Two recursive calls per call make a tree, and trees grow fast. The naive Fibonacci function calls itself twice, so fib(30) makes about 2.7 million calls and each +1 to n multiplies the work by about 1.6. That is exponential time.

The tree is wide but not deep. Only one path from the root to a leaf is on the call stack at any moment, so the depth, and the memory, is still about n frames.

Look at the tree and you see the waste: fib(3) is computed again and again with the same answer. Memoization fixes that. Keep a map from input to answer; on every call, look first, compute only on a miss, and store before returning. Each input is then computed once and the calls drop from exponential to about 2n.

The order matters: check the memo before recursing. A function that recurses first and checks afterwards gets the right answers at the old, exponential price. Memoization also costs memory, O(n) entries here, and it does not make the recursion any shallower.

Divide and conquer is branching done on purpose: split the input in half, solve each half, combine. If you must look at both halves (the largest number in a list), the tree has about 2n calls and you gain nothing in time, though the stack is only log₂ n deep.

The big win comes when you can throw one half away. Binary search compares the middle item of a sorted list with the target and recurses into one side only: about log₂ n calls, 20 for a million items. Every call must shrink the range, which is why the bounds are mid + 1 and mid - 1, never mid.

Unit 03 · 3 lessons

Recursion as choices

Model a problem as a tree of decisions and walk every branch

  1. 01Take it or leave it
  2. 02Every ordering
  3. BOSSChoose k
Unit prize
  1. 01
    Take it or leave it

    Two branches per item, 2ⁿ subsets

  2. 02
    Every ordering

    n choices, then n - 1, then n - 2

  3. BOSS
    Choose k

    Groups where order does not matter

Read the unit guide

Many problems are a series of decisions, and recursion can walk every combination of them. Draw the decisions as a tree: each level is one decision, each branch one option, and each leaf one complete outcome. A recursive call moves down one level.

Subsets are yes-or-no decisions. For each item, one branch takes it and one leaves it, so n items give 2ⁿ leaves. The tree is only n levels deep, so the stack stays small even when the output is huge.

Orderings are "which item next" decisions. With n items there are n options for the first slot, n - 1 for the second, and so on: n! leaves, which outgrows 2ⁿ almost immediately. When the items already chosen live in a shared set, each branch must choose, explore, then un-choose, so its siblings start from a clean state.

Combinations pick k items where order does not matter. To produce each group once, never look backward: pass a start index and only consider items after the last one picked. Passing i + 1 forbids reuse; passing i would allow the same item again.

Counting is often cheaper than listing. If you only need how many, branches can return numbers and add them, and sometimes a formula replaces the tree: 2 × bags(n - 1), or n × ways(n - 1).

All of these visit every leaf, so the cost is the size of the tree: O(2ⁿ) for subsets, O(n!) for orderings. That is fine for 20 items and hopeless for 60. The next unit is about not visiting leaves that cannot work.

Unit 04 · 3 lessons

Backtracking

Search with one shared path, undo every choice, and prune dead ends early

  1. 01Choose, explore, undo
  2. 02Prune early
  3. BOSSN-Queens
Unit prize
  1. 01
    Choose, explore, undo

    One shared path that every call cleans up

  2. 02
    Prune early

    Skip branches that cannot reach an answer

  3. BOSS
    N-Queens

    One queen per row, three sets, no attacks

Read the unit guide

Backtracking is recursion over choices with one shared piece of state. Instead of handing every call its own copy, all the calls edit the same path, and each one cleans up after itself.

The template has three steps around the recursive call. Choose: add an option to the path. Explore: recurse. Undo: take the option off again. After the undo, the path is exactly as the call found it, which is what lets the next option start clean.

Because the path is shared, saving it saves a reference, not a snapshot. Record a copy whenever you keep a result, or later undos will empty every answer you saved.

Pruning is what makes backtracking fast. Test a choice before you recurse and skip it when it cannot lead to an answer: a sum already past the target, a closing bracket with nothing open. With sorted candidates, the first one that is too big ends the whole loop.

N-Queens puts it all together. Place one queen per row, remember the used columns and both kinds of diagonal in sets (row − col and row + col), and back up as soon as a row has no safe square. A 4×4 board has exactly 2 solutions.

Learn Recursion & Backtracking on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy