Backtracking pattern for coding interviews
Backtracking builds candidate answers one choice at a time, explores what follows each choice, and undoes it before trying the next, so it can list every valid arrangement without storing them all. It fits problems that ask for all subsets, orderings, combinations or placements that satisfy rules. The skill interviewers look for is pruning: abandoning a partial answer as soon as it cannot succeed.
By Evin JohnPublished 7 min read
How to spot a backtracking problem
If the answer is a list of arrangements rather than a single number, you are probably enumerating, and backtracking is the tidy way to enumerate. Good clues are words like "all", "every" and "generate", small input limits such as n up to 10 or 15 (an exponential algorithm is expected), and rules that can be checked on a partial answer. If the question only wants a count or a best value and the same sub-question repeats, dynamic programming is often better; the dynamic programming patterns guide covers that switch.
Picture a decision tree. Each level is one decision, such as whether to include the next item or which item goes in the next position. A path from the root to a leaf is one candidate. Backtracking walks this tree depth first, keeping only the current path in memory, and pruning cuts whole branches the moment their path breaks a rule.
The template
go(state):
if state is a complete answer:
record a copy of it
return
for each choice allowed from this state:
if the choice cannot lead to an answer: skip (prune)
apply the choice # choose
go(new state) # explore
remove the choice # undoShape 1: subsets
To list every subset, pass a start index so each item can only be added after the ones already chosen. That stops [a, b] and [b, a] from both appearing. Every node of the tree, not just the leaves, is an answer, so record the path on entry.
def subsets(items):
out, path = [], []
def go(start):
out.append(path[:]) # every node is an answer
for i in range(start, len(items)):
path.append(items[i]) # choose
go(i + 1) # explore
path.pop() # undo
go(0)
return outfunction subsets(items) {
const out = [], path = [];
const go = start => {
out.push([...path]);
for (let i = start; i < items.length; i++) {
path.push(items[i]);
go(i + 1);
path.pop();
}
};
go(0);
return out;
}Shape 2: permutations
Order matters now, so any unused item may go next. Track which positions are used with a boolean list instead of a start index, and record only full-length paths.
def permutations(items):
out, path, used = [], [], [False] * len(items)
def go():
if len(path) == len(items):
out.append(path[:])
return
for i, x in enumerate(items):
if used[i]:
continue
used[i] = True; path.append(x)
go()
path.pop(); used[i] = False
go()
return outShape 3: combinations that reach a target, with pruning
Here is an example written for this page: list every way to make a total from coin values, where each value may be used any number of times and order does not matter. Sort the values, carry the amount still needed, and recurse with the same start index so a coin can repeat. Because the values are sorted, once one is larger than what is left, every later one is too, so the loop can stop. With coins [7, 4, 3] and a total of 11, the answers are 3+4+4 and 4+7.
def combos_to_total(coins, total):
coins = sorted(set(coins))
out, path = [], []
def go(start, left):
if left == 0:
out.append(path[:])
return
for i in range(start, len(coins)):
if coins[i] > left:
break # sorted, so the rest are too big
path.append(coins[i])
go(i, left - coins[i]) # i, not i + 1: a coin may repeat
path.pop()
go(0, total)
return outfunction combosToTotal(coins, total) {
const sorted = [...new Set(coins)].sort((a, b) => a - b);
const out = [], path = [];
const go = (start, left) => {
if (left === 0) { out.push([...path]); return; }
for (let i = start; i < sorted.length; i++) {
if (sorted[i] > left) break;
path.push(sorted[i]);
go(i, left - sorted[i]);
path.pop();
}
};
go(0, total);
return out;
}Constraint problems: rules checked on the way down
Some problems are less about choosing items and more about filling slots under rules. Generating every string of n balanced bracket pairs is a good small example: add an opening bracket while fewer than n are open, and a closing one only while it would not close more than were opened. No invalid string is ever built, which is pruning in its strongest form. Compare it with Valid Parentheses, which checks a given string with a stack.
def balanced(n):
out = []
def go(s, opened, closed):
if len(s) == 2 * n:
out.append(s)
return
if opened < n:
go(s + "(", opened + 1, closed)
if closed < opened:
go(s + ")", opened, closed + 1)
go("", 0, 0)
return outPlacing n queens on an n by n board so none attack each other works the same way: one queen per row, and before placing in a column, check three sets that record used columns and the two diagonal directions (row minus column, row plus column). Each check is O(1), so the pruning is cheap.
Example problems to practice
- All subsets, then all subsets of a list with duplicates. Sort first and skip an item equal to the previous one at the same tree level.
- All orderings, then orderings with duplicates. Same skip rule, applied to unused equal neighbors.
- Coin or number combinations to a total. The code above; the variant where each number may be used once uses i + 1 instead of i.
- Balanced bracket strings. The code above, a favorite because the pruning is visible.
- Word search in a letter grid. Depth-first from each cell, marking a cell visited on the way down and unmarking it on the way back, the same move as the flood fill in Number of Islands but with undo.
- Queens on a board. Row by row with column and diagonal sets.
Complexity
| Problem | Answers | Time | Extra space (excluding output) |
|---|---|---|---|
| Subsets of n items | 2^n | O(n × 2^n) including copies | O(n) recursion and path |
| Orderings of n items | n! | O(n × n!) including copies | O(n) |
| Combinations to a total T with smallest value m | Varies | Exponential in T / m in the worst case | O(T / m) depth |
| Balanced strings of n pairs | The n-th Catalan number | O(n) per string produced | O(n) |
Common mistakes
- Recording the path itself instead of a copy. Every stored answer then points at the same list, which ends up empty.
- Forgetting to undo. A missing pop or unmark leaks one branch's choice into its siblings.
- Using i + 1 when repeats are allowed, or i when they are not. Say which rule applies before coding.
- Pruning with continue when break is valid. On sorted input, once a value is too big, the rest are too; break saves real time.
- Duplicate answers from duplicate inputs. Sort and skip equal values at the same level, not across levels.
How to explain it out loud
Fictional example
- Candidate
- The question wants every combination, so the output itself can be exponential; I am aiming for an algorithm that does little work beyond producing it.
- Candidate
- I will build a combination one coin at a time, recurse with the remaining amount, then remove the coin and try the next. Passing a start index keeps each combination in sorted order, so I never produce the same set twice.
- Candidate
- I sort the coins first so I can stop the loop as soon as a coin exceeds the remaining amount. Space is the recursion depth, at most the total divided by the smallest coin.
Backtracking is depth-first search over a decision tree, so the graph traversal patterns guide is a natural companion; for questions that ask how many rather than which, see dynamic programming patterns. All walkthroughs are on the coding problems hub.
Practicing with Natively
In a practice session, Natively can read a backtracking problem from a screenshot on your Mac or Windows computer and outline the decision tree and a prune, which helps when you are stuck on where to cut. A transcript of your mock round shows whether you explained the undo step and the complexity. See the AI interview assistant.
Questions people ask
What is backtracking in coding interviews?
A depth-first way to build every valid arrangement one choice at a time: make a choice, recurse on what follows, then undo the choice and try the next. It is used for subsets, orderings, combinations and placement puzzles.
How do you recognize a backtracking problem?
The question asks for all or every possible arrangement, the input is small enough that an exponential answer is expected, and rules can be checked on a partial answer.
What is pruning in backtracking?
Stopping a branch as soon as its partial answer cannot succeed, such as a coin larger than the amount left. It does not change the worst-case class but can cut the work dramatically.
What is the difference between backtracking and dynamic programming?
Backtracking lists the arrangements themselves. Dynamic programming counts them or finds the best one by reusing answers to repeated sub-questions, which is usually much faster when only a number is needed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
