Search choices with choose, explore and undo, and cut dead branches early: combination sums, balanced brackets, word search and partitions.
Use it when you must find every answer that follows a rule, and many partial answers can be rejected early. Signal words: every combination, all valid, place without clashing.
Prune before you choose, reject a branch by a bound (the total is too large) or by validity (a rule is already broken).
Choose change the shared list or marks by one choice.
Explore call the same function for the next decision.
Undo restore what you changed. Save a copy when you keep an answer.
Cost the calls that survive the pruning. The worst case is still exponential, but real inputs are often far smaller.
In this lesson you search for answers with choose, explore and undo, and you cut a branch the moment it cannot lead to an answer. You see real counts of the calls saved, and you handle equal items.
You work on the gift-box page of an online store. A shopper enters a budget, and the page lists every set of items whose prices add up to exactly that budget.
Your team lead says: Show every box that fits the budget, and do not make the shopper wait.
Here is a short check. The prices are 2, 3, 5 and 6 units, and the budget is 8 units. Two boxes fit: 2 and 6, and 3 and 5.
So the task is this: find every set of prices that adds up to the budget, and stop searching a set the moment it cannot work.
A visitor explores a maze of corridors. At each fork the visitor draws a chalk mark and walks down one corridor. At a dead end, the visitor rubs out the mark and returns to the fork.
A sign at some forks says "closed ahead". The visitor does not enter those corridors at all, so no time is lost in them.
The chalk is choose and undo. The walk is explore. The sign is pruning: a rule that rejects a branch before you enter it.
A visitor in a maze marks the path with chalk, rubs the mark out at a dead end, and never enters a corridor with a closed sign.
Before you write code, find the boxes for prices 2, 3, 5 and 6 and a budget of 8. Add one price at a time, from the smallest, and stop a box when the next price is too large.
Solve it by hand: The bundles of four prices for a budget of 8. The hand-solve sheet loads in your browser.
Every call has one budget left to pay. A call with nothing left to pay saves the box it holds.
Each row is one take of a price. The prices are sorted, so a price that is too large cuts every price after it.
| Take | Chosen prices | Left to pay | What happens next |
|---|---|---|---|
| 2 | [2] | 6 | tries 3, 5 and 6 after the 2 |
| 3 | [2, 3] | 3 | price 5 is more than 3, so 5 and 6 are cut |
| 5 | [2, 5] | 1 | price 6 is more than 1, so it is cut |
| 6 | [2, 6] | 0 | saves the box [2, 6] |
| 3 | [3] | 5 | tries 5, then 6 is cut |
| 5 | [3, 5] | 0 | saves the box [3, 5] |
| 5 | [5] | 3 | price 6 is more than 3, so it is cut |
| 6 | [6] | 2 | nothing after 6 is left to try |
The two boxes are [2, 6] and [3, 5]. The search made 9 calls, and it never added 5 and 6 together.
Start with a correct version. It builds every subset of the prices with a bit mask, and keeps the subsets whose total equals the budget.
def bundles(prices, budget):
found = []
for mask in range(1, 1 << len(prices)): # every non-empty subset
picked = [prices[i] for i in range(len(prices)) if mask >> i & 1]
if sum(picked) == budget: # keep it only if it adds up exactly
found.append(picked)
return foundThis is correct. The team keeps it as the reference. The question is how it behaves when the price list grows.
Now check the real size.
A gift-box page can offer 30 or more items.
Run the function, in Python, on the 22 even prices 4, 6, 8, ..., 46 and a budget of 50, and look at the numbers:
Predict the saving
Q For 22 prices the first attempt checks 4,194,303 subsets. A search that stops a box when its total passes the budget makes 488 calls and finds the same 75 boxes. About how many subsets does the first attempt check for each call of the search?
Answer: C
The search makes 488 calls and the first attempt checks 4,194,303 subsets. The ratio is 8,594.9, so the first attempt does thousands of checks for every call of the search.
The first attempt is correct, and almost all of its work is spent on sets that went over the budget long ago. A search can leave those sets alone.
Build each box one price at a time, from the smallest price. When a price is larger than what is left to pay, every later price is larger too, so the whole rest of the loop is cut. Look at the calls for the four prices as a tree.
Four prices and a budget of eight make a tree of 9 calls, where the full skip-or-take tree has 31 calls.
Exercise · Predict the output: Which calls does the search make?. The prices are 1, 2, 2 and 3, and the budget is 5. Each call prints what is left to pay when it starts. Which line does the search print?
def walk(prices, start, remaining):
print(remaining)
if remaining == 0:
return
for i in range(start, len(prices)):
if prices[i] > remaining:
break
if i > start and prices[i] == prices[i - 1]:
continue
walk(prices, i + 1, remaining - prices[i])
walk([1, 2, 2, 3], 0, 5)The tree has 9 calls and 2 leaves that save a box. The full skip-or-take tree for 4 prices has 31 calls. The search never entered the calls for sets that already cost more than 8.
Pruning does not change the answer. It changes how many calls you make to reach it. Here are real counts for the same search on longer price lists.
| Prices | Budget | Subsets in all | Calls made by the pruned search | Boxes found |
|---|---|---|---|---|
| 22 prices: 4, 6, 8, ..., 46 | 50 | 4,194,303 | 488 | 75 |
| 30 prices: 4, 7, 10, ..., 91 | 60 | 1,073,741,824 | 284 | 21 |
| 40 prices: 5, 7, 9, ..., 83 | 100 | 1,099,511,627,776 | 12,066 | 712 |
Pruning by a bound is one kind. The other kind is pruning by validity: you refuse a choice that already breaks a rule. Queens on a board are the standard example, because no two may share a column or a diagonal.
Race: Queen searches on an n by n board, counted by running both. The operation counter loads in your browser.
The race counts the calls of two queen searches on boards of 4 to 7 squares a side. Both find the same placements. For a 7 by 7 board the search without pruning makes 960,800 calls and the pruned search makes 552.
The call is bundles([1, 1, 2, 3], 4). The player stops at five steps and asks you to predict.
Dry run: Predict each step: the bundles of 1, 1, 2, 3 for a budget of 4. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row. The row is the box that a call saves, in order.
| Box number | Box | Calls so far |
|---|---|---|
| 1 | [1, 1, 2] | 4 |
| 2 | [1, 3] | 6 |
The second 1 at the top of the loop is skipped, because the first 1 already made every box that starts with 1. The search ends after 8 calls.
Pruning is a bet that most branches are dead. In the table above, 40 prices needed 12,066 calls for 712 boxes. The cost depends on the data, so always measure it on realistic input.
Here is the rule that keeps the search correct. Every line of the templates exists to protect it.
A branch is cut only when no answer can lie inside it, and each call restores the shared list and marks exactly as it found them.
A prune that cuts a branch with an answer is a bug, and the answers go missing without any error. A prune that is too weak is only slow. So write the strongest rule that you can prove safe.
Use it when you must find every answer that follows a rule, and many partial answers can be rejected early. Signal words: every combination, all valid, place without clashing.
Prune: before you choose, reject a branch by a bound (the total is too large) or by validity (a rule is already broken).
Choose: change the shared list or marks by one choice.
Explore: call the same function for the next decision.
Undo: restore what you changed. Save a copy when you keep an answer.
Cost: the calls that survive the pruning. The worst case is still exponential, but real inputs are often far smaller.
Sort the prices, and choose from a start position that only moves forward. Cut the loop when a price is too large, and skip a price equal to the one tried before it at the same step.
def bundles(prices, budget):
found = []
walk(sorted(prices), 0, budget, [], found)
return found
def walk(prices, start, remaining, chosen, found):
# [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if remaining == 0:
found.append(list(chosen))
return
for i in range(start, len(prices)):
# [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if prices[i] > remaining:
break
# [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if i > start and prices[i] == prices[i - 1]:
continue
# [4] Choose the price, and explore with the smaller remainder.
chosen.append(prices[i])
walk(prices, i + 1, remaining - prices[i], chosen, found)
# [5] Undo the choice, so the next price starts from the same bundle.
chosen.pop()public int[][] bundles(int[] prices, int budget) {
int[] sorted = prices.clone();
Arrays.sort(sorted);
List<int[]> found = new ArrayList<>();
walk(sorted, 0, budget, new ArrayList<>(), found);
return found.toArray(new int[0][]);
}
private void walk(int[] prices, int start, int remaining, List<Integer> chosen, List<int[]> found) {
// [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if (remaining == 0) {
found.add(chosen.stream().mapToInt(Integer::intValue).toArray());
return;
}
for (int i = start; i < prices.length; i++) {
// [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if (prices[i] > remaining) {
break;
}
// [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if (i > start && prices[i] == prices[i - 1]) {
continue;
}
// [4] Choose the price, and explore with the smaller remainder.
chosen.add(prices[i]);
walk(prices, i + 1, remaining - prices[i], chosen, found);
// [5] Undo the choice, so the next price starts from the same bundle.
chosen.remove(chosen.size() - 1);
}
}void walk(const vector<int>& prices, int start, int remaining, vector<int>& chosen, vector<vector<int>>& found) {
// [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if (remaining == 0) {
found.push_back(chosen);
return;
}
for (int i = start; i < (int)prices.size(); i++) {
// [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if (prices[i] > remaining) {
break;
}
// [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if (i > start && prices[i] == prices[i - 1]) {
continue;
}
// [4] Choose the price, and explore with the smaller remainder.
chosen.push_back(prices[i]);
walk(prices, i + 1, remaining - prices[i], chosen, found);
// [5] Undo the choice, so the next price starts from the same bundle.
chosen.pop_back();
}
}
vector<vector<int>> bundles(vector<int> prices, int budget) {
sort(prices.begin(), prices.end());
vector<vector<int>> found;
vector<int> chosen;
walk(prices, 0, budget, chosen, found);
return found;
}function walk(prices, start, remaining, chosen, found) {
// [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if (remaining === 0) {
found.push(chosen.slice());
return;
}
for (let i = start; i < prices.length; i++) {
// [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if (prices[i] > remaining) {
break;
}
// [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if (i > start && prices[i] === prices[i - 1]) {
continue;
}
// [4] Choose the price, and explore with the smaller remainder.
chosen.push(prices[i]);
walk(prices, i + 1, remaining - prices[i], chosen, found);
// [5] Undo the choice, so the next price starts from the same bundle.
chosen.pop();
}
}
function bundles(prices, budget) {
const found = [];
walk(prices.slice().sort((a, b) => a - b), 0, budget, [], found);
return found;
}Rebuild the template: put its lines back in order. Loads in your browser.
The prices are sorted, so the boxes come out in order. The answer for [2, 3, 5, 6] and a budget of 8 is the two boxes of the dry run.
The combination template saves a box when nothing is left, cuts the loop at a price that is too large, and skips an equal sibling.
Exercise · Find the bug: The box that fits exactly. This counts the boxes whose prices add up to the budget. It misses boxes on some inputs, always the ones with a price that uses up the whole remainder. Which line is wrong?
def count_boxes(prices, start, remaining):
if remaining == 0:
return 1
total = 0
for i in range(start, len(prices)):
if prices[i] >= remaining:
break
if i > start and prices[i] == prices[i - 1]:
continue
total += count_boxes(prices, i + 1, remaining - prices[i])
return totalBuild the text one bracket at a time. An open bracket is allowed while some are left to open. A close bracket is allowed only while one is open. No invalid text is ever built.
def all_brackets(pairs):
found = []
extend(pairs, 0, 0, [], found)
return found
def extend(pairs, opened, closed, text, found):
# [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if len(text) == 2 * pairs:
found.append("".join(text))
return
# [2] Open a bracket only while some are left to open, then explore and undo.
if opened < pairs:
text.append("(")
extend(pairs, opened + 1, closed, text, found)
text.pop()
# [3] Close a bracket only while one is open, then explore and undo.
if closed < opened:
text.append(")")
extend(pairs, opened, closed + 1, text, found)
text.pop()public String[] allBrackets(int pairs) {
List<String> found = new ArrayList<>();
extend(pairs, 0, 0, new StringBuilder(), found);
return found.toArray(new String[0]);
}
private void extend(int pairs, int opened, int closed, StringBuilder text, List<String> found) {
// [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if (text.length() == 2 * pairs) {
found.add(text.toString());
return;
}
// [2] Open a bracket only while some are left to open, then explore and undo.
if (opened < pairs) {
text.append('(');
extend(pairs, opened + 1, closed, text, found);
text.deleteCharAt(text.length() - 1);
}
// [3] Close a bracket only while one is open, then explore and undo.
if (closed < opened) {
text.append(')');
extend(pairs, opened, closed + 1, text, found);
text.deleteCharAt(text.length() - 1);
}
}void extend(int pairs, int opened, int closed, string& text, vector<string>& found) {
// [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if ((int)text.size() == 2 * pairs) {
found.push_back(text);
return;
}
// [2] Open a bracket only while some are left to open, then explore and undo.
if (opened < pairs) {
text.push_back('(');
extend(pairs, opened + 1, closed, text, found);
text.pop_back();
}
// [3] Close a bracket only while one is open, then explore and undo.
if (closed < opened) {
text.push_back(')');
extend(pairs, opened, closed + 1, text, found);
text.pop_back();
}
}
vector<string> allBrackets(int pairs) {
vector<string> found;
string text;
extend(pairs, 0, 0, text, found);
return found;
}function extend(pairs, opened, closed, text, found) {
// [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if (text.length === 2 * pairs) {
found.push(text.join(""));
return;
}
// [2] Open a bracket only while some are left to open, then explore and undo.
if (opened < pairs) {
text.push("(");
extend(pairs, opened + 1, closed, text, found);
text.pop();
}
// [3] Close a bracket only while one is open, then explore and undo.
if (closed < opened) {
text.push(")");
extend(pairs, opened, closed + 1, text, found);
text.pop();
}
}
function allBrackets(pairs) {
const found = [];
extend(pairs, 0, 0, [], found);
return found;
}Exercise · Put it in order: How many balanced texts?. Arrange the lines into a search that counts the balanced texts you can still finish, given how many pairs there are and how many brackets are open and closed so far.
def count_brackets(pairs, opened, closed):
if closed == pairs: return 1
total = 0
if opened < pairs: total += count_brackets(pairs, opened + 1, closed)
if closed < opened: total += count_brackets(pairs, opened, closed + 1)
return total
if closed < pairs: total += count_brackets(pairs, opened, closed + 1)
if opened == pairs: return 1For 3 pairs the search makes 22 calls and finds 5 texts. The full tree of every text of 6 brackets has 127 calls. For 10 pairs the search makes 82,499 calls and finds 16,796 texts, against 2,097,151 calls for the full tree.
Place one queen in each row. Marks say which columns and diagonals are taken, so a call tries only squares that are still free.
def count_queens(n):
return place(n, 0, [False] * n, [False] * (2 * n), [False] * (2 * n))
def place(n, row, cols, down, up):
# [1] Base case: every row has a queen, so this placement counts once.
if row == n:
return 1
total = 0
for col in range(n):
# [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if cols[col] or down[row + col] or up[row - col + n - 1]:
continue
# [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = True
# [4] Explore the next row.
total += place(n, row + 1, cols, down, up)
# [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = False
return totalpublic int countQueens(int n) {
return place(n, 0, new boolean[n], new boolean[2 * n], new boolean[2 * n]);
}
private int place(int n, int row, boolean[] cols, boolean[] down, boolean[] up) {
// [1] Base case: every row has a queen, so this placement counts once.
if (row == n) {
return 1;
}
int total = 0;
for (int col = 0; col < n; col++) {
// [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if (cols[col] || down[row + col] || up[row - col + n - 1]) {
continue;
}
// [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = true;
// [4] Explore the next row.
total += place(n, row + 1, cols, down, up);
// [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = false;
}
return total;
}int place(int n, int row, vector<bool>& cols, vector<bool>& down, vector<bool>& up) {
// [1] Base case: every row has a queen, so this placement counts once.
if (row == n) {
return 1;
}
int total = 0;
for (int col = 0; col < n; col++) {
// [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if (cols[col] || down[row + col] || up[row - col + n - 1]) {
continue;
}
// [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = true;
// [4] Explore the next row.
total += place(n, row + 1, cols, down, up);
// [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = false;
}
return total;
}
int countQueens(int n) {
vector<bool> cols(n, false), down(2 * n, false), up(2 * n, false);
return place(n, 0, cols, down, up);
}function place(n, row, cols, down, up) {
// [1] Base case: every row has a queen, so this placement counts once.
if (row === n) {
return 1;
}
let total = 0;
for (let col = 0; col < n; col++) {
// [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if (cols[col] || down[row + col] || up[row - col + n - 1]) {
continue;
}
// [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = true;
// [4] Explore the next row.
total += place(n, row + 1, cols, down, up);
// [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = false;
}
return total;
}
function countQueens(n) {
return place(n, 0, new Array(n).fill(false), new Array(2 * n).fill(false), new Array(2 * n).fill(false));
}For an 8 by 8 board the search finds 92 placements in 2,057 calls. The same search with no pruning makes 19,173,961 calls, and it checks the board only at the end.
A parcel locker holds weights of 10, 30, 20, 40 and 20 kilograms. A courier wants every set of parcels that weighs exactly 60. Use the combination template with the weights as prices, and 60 as the budget. Each number below was measured by running the function.
| Weights | Target | Calls | Sets found |
|---|---|---|---|
| 10, 30, 20, 40, 20 | 60 | 13 | [10, 20, 30] and [20, 40] |
The weights are sorted to 10, 20, 20, 30, 40. The second 20 is skipped at the top, so the set [20, 40] appears once. The bound cuts 40 as soon as less than 40 is left.
The cost is the number of calls that survive the pruning, times the work to copy one answer. No rule can promise less than the size of the answer. In the worst case the bound cuts nothing, and the search is as large as the full tree.
Real production data brings edge cases.
For bundles([2, 4], 3), no box fits. The search makes 2 calls, finds nothing, and returns an empty list. The first price 2 is allowed, but then 4 is cut, so no box is found.
The call bundles([1, 1, 2, 2, 3, 3, 4], 6) has 5 different boxes: [1, 1, 2, 2], [1, 1, 4], [1, 2, 3], [2, 4] and [3, 3]. If every price is treated as different, the search finds 13 boxes. Skipping an equal sibling at the same step removes the repeats.
For bundles([2, 3], 0), the base case answers at once: the empty box costs 0, so the result is [[]]. In the product, a budget starts above 0, so the search never sees this input.
For bundles(prices, 100) with the 40 odd prices 5, 7, ..., 83, the search made 12,066 calls. The full tree has 1,099,511,627,776 subsets. The deepest chain has 9 calls, so the stack is safe.
This version stops the loop at the first price above the remainder, but it does not sort the prices first.
Counterexample: for the prices [6, 2, 3] and a budget of 5, the first price 6 is above 5, so the loop stops. It returns an empty list, but the box [2, 3] fits.
The bound is safe only when every later price is at least as large. Sort first.
For the unsorted prices 6, 2, 3 and a budget of 5, stopping at the first large price returns nothing, but the box 2 and 3 fits.
This version skips a price equal to the previous one with the test i > 0, and not i > start.
Counterexample: for the prices [1, 1, 2] and a budget of 4, it returns an empty list. The box [1, 1, 2] needs both 1s, and the second 1 is skipped below the first.
The skip applies only to a sibling at the same step, so the test is i > start.
This version of the queens search marks the column and diagonals, but never clears them after the call.
Counterexample: for 4 queens it returns 0, but there are 2 placements. For 8 queens it returns 0, but there are 92. The marks of the first branch block every later branch.
Clear the marks in the same call that set them.
Exercise · Break it: Find the prices that count a box twice. This counts the boxes whose prices add up to the budget, with each price used once. The shop sells items with equal prices, and the count looks too high. Find prices and a budget where it gives the wrong answer.
def count_bundles(prices, budget):
return walk(sorted(prices), 0, budget)
def walk(prices, start, remaining):
if remaining == 0:
return 1
total = 0
for i in range(start, len(prices)):
if prices[i] > remaining:
break
total += walk(prices, i + 1, remaining - prices[i])
return totalFor the prices 1 to 26 and a budget of 175, which is half the total, the search made 33,554,432 calls. The full set of subsets has 67,108,864. The bound cut only half of the tree.
For a budget of 40 on the same prices it made 8,322 calls. When many partial sets can still reach the target, look for another method, such as the dynamic programming of a later module.
Your team lead brings four product changes. Each one uses the same four steps.
The store sells items that repeat in price. Sort, and skip an equal sibling at the same step (LeetCode 40: Combination Sum II).
A gift box may hold several of the same item. Pass the same start position to the next call (LeetCode 39: Combination Sum).
A template engine needs every balanced set of nested blocks. Open while some are left, close while one is open (LeetCode 22: Generate Parentheses).
A seating tool must place guests so that none clash. Mark the rows, columns and diagonals that are taken (LeetCode 51: N-Queens).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain how backtracking with pruning finds every answer, and why a prune must never cut a branch that holds an answer. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I choose one item, explore the rest, and undo the choice. Before I choose, I reject any branch that already breaks the rule.
For a total I sort the items and stop the loop at the first one that is too large. For brackets and queens I refuse a choice that is already invalid.
A prune is safe only when no answer can lie in the branch it cuts. For equal items I skip an equal sibling at the same step.
I search with choose, explore and undo. Before each choice I ask whether any answer can still lie in that branch. If not, I cut it.
For a target total I sort the items and stop the loop at the first item that is too large. For brackets I open only while some are left, and close only while one is open. For queens I skip a square whose column or diagonal is taken.
The cost is the number of calls that survive, and I measure it. A prune must never cut a branch that holds an answer. For equal items I sort and skip an equal sibling at the same step.
Checkpoint · Backtracking with pruning
Q1/10 What does pruning add to choose, explore and undo?
Answer: B
The prune runs before the choice. A rejected branch is never entered, so its calls are never made.
Q2/10 For the prices 2, 3, 5 and 6 and a budget of 8, how many calls does the bound-pruned search make, and which boxes does it find?
Answer: B
The hand trace has 9 calls. The full skip-or-take tree has 31 calls, but the search never enters most of them.
Q3/10 For 22 prices the first attempt checks 4,194,303 subsets and the pruned search makes 488 calls. About how many subsets does the first attempt check for each call?
Answer: C
The ratio is 4,194,303 divided by 488, which is about 8,595.
Q4/10 Why must the prices be sorted before the loop stops at the first price that is too large?
Answer: C
The stop is safe only when no later price can fit. Sorting guarantees that every later price is at least as large.
Q5/10 The loop stops at the first price above what is left, but the prices [6, 2, 3] are not sorted. What does a search for a budget of 5 return?
Answer: C
The first price 6 is above 5, so the loop stops before it reaches 2 and 3. The box [2, 3] is lost without any error.
Q6/10 When does the bracket search close a bracket?
Answer: C
A close bracket needs an open one to match. The test is that closed is less than opened, so no invalid text is ever built.
Q7/10 For 8 queens, how many calls does the pruned search make, and how many placements does it find?
Answer: C
The pruned search found 92 placements in 2,057 calls. The same search with no pruning made 19,173,961 calls.
Q8/10 The prices are [1, 1, 2] and the budget is 4. Which test skips equal prices correctly?
Answer: B
The test i > start skips only a sibling at the same step. The test i > 0 also skips the second 1 below the first, and loses the box [1, 1, 2].
Q9/10 A queens search sets the column and diagonal marks but never clears them. What does it return for 4 queens?
Answer: C
The correct count is 2. Without the undo, a placed queen stays marked, and the run returns 0.
Q10/10 For the prices 1 to 26 and a budget of 175, the pruned search made 33,554,432 calls, and there are 67,108,864 subsets. What does this show?
Answer: C
When many partial boxes can still reach the budget, the bound cuts little. Measure the calls on real input.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Combinations without reuse | Pay | Medium | Sorting, the bound, and skipping an equal sibling |
| 2 | Generate balanced parentheses | Platform | Medium | Pruning by validity, and output order |
| 3 | Word in a letter grid | Chat | Medium | Marks on a grid, and pruning on a wrong letter |
| 4 | Combination sum of invoice items | Bank | Medium | Reusing an item, and a bound that cuts the loop |
| 5 | Words a phone keypad can spell | Search | Medium | Pruning with a set of prefixes |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.