Skip to main content

Backtracking

What backtracking means, when trying a path, undoing it, and trying another is exactly what the problem needs.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

Backtracking means trying one choice, seeing where it goes, and backing up when that path does not work.

It is a pattern of:

  • choose
  • explore
  • undo

When to use it

It appears when the problem asks you to enumerate possibilities under constraints:

  • combinations
  • permutations
  • sudoku
  • valid path search

Common mistake

The classic mistake is treating backtracking as just recursion.

Recursion is often the tool.

Backtracking is the strategy of trying and undoing choices.

Better question

Before applying it, ask:

  1. am I exploring many possible choices?
  2. can I prune a path early?
  3. do I need to undo state when I return?

Keep exploring