Skip to main content
Interview

Backtracking problems - my approach that works every time

Sachin AhujaSachin Ahuja
11 months ago
182

After struggling with backtracking for weeks, I developed this mental framework:

  1. What are my choices at each step?
  2. What constraints must I satisfy? (when to prune)
  3. What does the base case look like? (when am I done)

Then the template is always:

def backtrack(current_state, choices_left):
    if is_solution(current_state):
        save_result()
        return
    for choice in choices_left:
        if is_valid(choice):
            make_choice()
            backtrack(new_state, remaining_choices)
            undo_choice()

This worked for: N-Queens, Sudoku, Permutations, Subsets, Combination Sum, Word Search, and Palindrome Partitioning.

Hope this helps someone!


backtrackingpatternstutorialdsa

Comments (4)

Sign in to join the discussion.
Tanvi Ahuja
Tanvi Ahuja9 months ago

I used a similar approach for the Word Search problem. The challenge was handling the board state efficiently. Any advice on optimizing board traversal?

Mark Tanaka
Mark Tanaka10 months ago

I think this is a great starting point, but sometimes the pruning can be more complex than it seems. How do you ensure you’re not pruning valid possibilities?

Ryan Anderson
Ryan Anderson11 months ago

This is super helpful! I've always struggled with remembering all the steps for backtracking. Do you have any tips on how to efficiently determine when a choice is valid?

Saumya Yadav
Saumya Yadav11 months ago

This framework looks solid but sometimes I find it difficult to undo the choice correctly. Any pointers on how to handle complex states?