Backtracking: Attempt and Reversion

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Backtracking explores a decision tree: make a choice, proceed recursively, undo the choice, try the next alternative.

It is trial and error with systematic retreat. Without undo, incorrect partial states remain.

Diagram

Undo choices: Permutations [1].

Where used

Constraint solvers, Sudoku/planning, feature toggle combinations, regex engines (with cuts), game search. The try and undo pattern is behind many NP-hard exact solvers.

Depth

Backtracking searches a tree of partial decisions. Each node describes a partially constructed candidate, and each edge adds a choice. After an unsuccessful branch, the previous state is restored so that the next branch starts under the same initial conditions.

The central invariant is: upon entering a recursion level, the state contains exactly the decisions of the current path. Feasibility tests can prune branches early. Their quality often determines the runtime more strongly than the actual recursion, although the number of possible paths remains exponential in the worst case.

Difficulty levels

  1. Draw a complete decision tree for a few choices.
  2. Formulate a feasibility test that does not discard a valid solution.
  3. Choose search order and bounds to exclude large subtrees early.

Pitfalls

Often, changes are not fully undone, or global data is shared between sibling branches. An overly aggressive cut is also incorrect: it may seemingly improve runtime but can silently remove solutions.


Sources

University approvals: 0
Tasks
Question 1

What is the core step after a failed branch?

Question 2

A search branch adds a number to a common list. What must hold true before the next alternative?

Question 3

Implement existsSubset recursively with the decisions "Include element" and "Exclude element".

Hint

A private static helper method can receive an index and a remainder. Multiple boolean calls can be combined with ||.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy