π§© Python DSA Patterns β Backtracking Basics π
Posted on: November 21, 2025
Description:
Backtracking is a technique for exploring all possible configurations of a problem. It builds solutions step by step, and whenever a path is invalid, it backtracks β undoing the last step and trying something else.
Itβs the backbone of problems like subsets, permutations, N-Queens, Sudoku solving, and maze paths.
β¨ When to Use
- When the solution must be built incrementally.
- When you need to explore all combinations/permutations.
- When constraints may invalidate partial solutions.
- When brute force exists, but can be pruned with smart decisions.
β‘ Advantages
- Finds all valid solutions.
- Simple recursive pattern.
- Works great when combined with pruning (constraints to cut branches).
β Limitations
- Exponential time in worst cases.
- Needs careful pruning to avoid TLE.
π Example 1 β Generate All Subsets
Classic backtracking: choose or skip each element.
def subsets(nums):
result = []
subset = []
def backtrack(i):
if i == len(nums):
result.append(subset.copy())
return
# include element
subset.append(nums[i])
backtrack(i + 1)
# exclude element
subset.pop()
backtrack(i + 1)
backtrack(0)
print("Subsets:", result)
subsets([1, 2, 3])
# Output: all subsets of [1,2,3]
π Example 2 β Generate All Permutations
All orderings of elements β swap-based or choose-based pattern.
def permutations(nums):
result = []
used = [False] * len(nums)
current = []
def backtrack():
if len(current) == len(nums):
result.append(current.copy())
return
for i in range(len(nums)):
if not used[i]:
used[i] = True
current.append(nums[i])
backtrack()
current.pop()
used[i] = False
backtrack()
print("Permutations:", result)
permutations([1, 2, 3])
π Example 3 β N-Queens (Conceptual Intro)
N-Queens places 1 queen per row so that no two queens attack each other.
Only showing the structure here β actual solution goes deep, but follows the same backtracking template.
# Structure:
# place queen row by row
# try each column
# if safe β recurse to next row
# if unsafe β backtrack
This is one of the best problems to learn pruning.
π§ Backtracking Template (General Form)
def backtrack(path, choices):
if goal_reached(path):
save(path)
return
for choice in choices:
if is_valid(choice, path):
apply(choice, path)
backtrack(path, choices)
undo(choice, path) # backtrack step
Almost every backtracking problem maps to this template.
π§ Where It Helps
- π’ Subsets, Combinations
- π Permutations
- βοΈ N-Queens, Sudoku, Crossword fill
- πΊοΈ Maze solving (all paths)
- π€ Word search in grids
- π§© Constraint satisfaction problems
β Takeaways
- Backtracking = recursion + undoing last choice.
- Builds solutions incrementally.
- Use pruning to skip invalid paths early.
- Extremely powerful for generation & search problems.
ποΈ Practice Problems
- Subsets
- Permutations
- Combination Sum
- N-Queens
- Word Search
No comments yet. Be the first to comment!