Backtracking

Problem shape

Intermediate
4
8
15
16
23
42
Core idea

Build a candidate, recurse, then undo the choice when returning.

Step 1 / 5
Problem shape
Current lesson

Backtracking Lab

Backtracking Intermediate

Backtracking

Welcome to the Backtracking algorithm lab. Build a candidate, recurse, then undo the choice when returning. Use it when: Use for permutations, subsets, combinations, constraints, and search spaces. The time complexity is Often exponential, and the space complexity is O(depth). The pseudocode is: search(state) if complete(state) record state for choice in choices if valid(choice) apply choice search(state) undo choice As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

Often exponential

Space

O(depth)

Pseudocode

search(state)
  if complete(state) record state
  for choice in choices
    if valid(choice)
      apply choice
      search(state)
      undo choice
Open deeper structure lesson
1.0x