Lesson

Backtracking

DFS through a decision tree with undo — generate combinations and permutations.

Medium → HardTime O(2^n)–O(n!)Space O(n)
Practice problems
Loading visualization…

Loading solution…

Template

Build a path. At each index, decide to include or skip (or try each candidate). Recurse, then pop to undo.

Pruning

Skip when remaining capacity is negative, when duplicates would repeat a branch, or when a partial board is already invalid.

Pitfalls

  • !Forgetting to unchoose
  • !Duplicate branches
  • !Mutating shared lists without copy on save

Practice from this topic

Showing 24 of the related problems in the 1000-question bank.

View all →

Got the lesson?

Mark Backtracking as understood when the ideas stick.