Intermediate Topic 29 of 51 Algorithms
Backtracking
Building solutions incrementally and abandoning dead ends.
How it works
Backtracking builds candidate solutions incrementally and abandons a partial candidate as soon as it cannot lead to a valid solution, then undoes the last choice and tries another. It explores the decision tree depth-first, and pruning strongly cuts the number of nodes visited. Worst-case time remains exponential, but good constraints make it practical.
Step-by-step walkthrough
- Build a solution one choice at a time.
- Go deeper with the next choice.
- A constraint fails, this is a dead end.
- Undo the last choice and return to the previous state.
- Try the next option, which leads to a valid solution.
Where it is used
Solving Sudoku, N-queens, generating permutations and combinations, word searches, maze solving, constraint satisfaction and parsing with alternatives use backtracking.
Common pitfall
Forgetting to undo state changes before trying the next choice corrupts the search. Weak pruning makes it as slow as brute force. Check constraints as early as possible, order choices to fail fast and avoid recomputing duplicates, using memoization if subproblems repeat.
Where it fits in the course
Backtracking is topic 29 of 51 in Algorithms, rated Intermediate. It follows Edit Distance. The next topic is N-Queens Problem.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Backtracking?
Where do people use Backtracking?
What is the most common mistake with Backtracking?
What should I learn before this topic?
How can I practice it?
Is Backtracking hard to learn?
How long does it take to learn Backtracking?
Which topics are related to Backtracking?
What should I study after Backtracking?
Related topics
- Edit Distance (Algorithms)
- N-Queens Problem (Algorithms)
- Longest Common Subsequence (Algorithms)
- Breadth-First Search (Algorithms)