Pattern · 14 problems
Backtracking Interview Problems
Backtracking builds an answer one choice at a time and undoes the choice afterward. Pruning keeps it affordable.
Free: write the code and run it, no sign-up.
When I reach for it
- The question asks for all combinations, permutations or placements.
- You make a choice, explore it, and may need to take it back.
- Brute force is exponential, and the interviewer expects that.
Problems, easiest first
0 easy · 10 medium · 4 hard. Open one to read it, then write it in the free editor.
- Combination SummediumArrays & Hashing
- Word SearchmediumStringsBFS & DFS
- Combination Sum IImediumArrays & Hashing
- Generate ParenthesesmediumDynamic ProgrammingStrings
- Letter Combinations of a Phone NumbermediumStringsArrays & Hashing
- Palindrome PartitioningmediumDynamic ProgrammingStrings
- PermutationsmediumArrays & Hashing
- SubsetsmediumBit ManipulationArrays & Hashing
- Subsets IImediumBit ManipulationArrays & Hashing
- Target SummediumDynamic ProgrammingArrays & Hashing
- Word Search IIhardTreesStrings
- N-QueenshardArrays & Hashing
- Reconstruct ItineraryhardGraphsBFS & DFS
- Regular Expression MatchinghardDynamic ProgrammingStrings
The idea
Build the answer one choice at a time. If a choice breaks a rule, stop that branch early. After exploring a choice, undo it so the next one starts clean.
Answer three questions first. What is a choice? When is a path complete? When can I prune?
def search(start, path, remaining):
if remaining == 0:
results.append(path[:]) # copy: path keeps changing
return
for i in range(start, len(nums)):
if nums[i] > remaining:
continue # prune this branch
path.append(nums[i]) # choose
search(i, path, remaining - nums[i]) # explore; i allows reuse
path.pop() # un-chooseWhere it goes wrong
- Recording the path itself instead of a copy of it.
- Forgetting to undo the choice.
- Duplicates in the input. Sort first and skip repeated values at the same level.
Say this before you type. Say the choice, the stopping rule, and the earliest moment you can prune.
Where Coco comes in
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.
Questions people ask
- How is backtracking different from dynamic programming?
- Backtracking lists every answer. Dynamic programming counts or optimizes by reusing answers to repeated subproblems. If subproblems repeat, cache them.
- How do I avoid duplicate results?
- Sort the input, then skip a value that equals the one before it at the same depth. Each distinct choice is tried once.
Meet these next
Fin and Coco are characters, not people. strongyes.io is independent. Leo builds it with AI agents.
