Four problems that cut an input into pieces or groups. The move: build the split piece by piece, reject a piece the moment it cannot work, and drop branches that repeat the same state.
You work on a billing system, a text tool and a workshop planner. The four problems on this street cut an input into pieces or put items into groups. Every item is used exactly once, and every piece or group must obey a rule.
The Academy lessons Backtracking with pruning and Subsets and permutations give choose, explore and undo. Read the table by its last two columns. They say when a branch ends and what the search returns.
| Problem | The cut or the group | A branch ends when | The search returns |
|---|---|---|---|
| Split a string into valid sums | pieces of digits, left to right | a piece starts with 0, or the sum passes the target | how many cuts |
| Split into palindromes | pieces that read the same both ways | a piece is not a palindrome | one page of splits |
| Matchsticks into a square | strips on four sides | a side has no room left | the largest area |
| Partition into k equal groups | payouts in batches of equal total | a batch overflows | the largest number of batches |
Exercise · Predict the output: Cuts that add up to 39. A cut splits the digits into pieces from left to right, and the pieces must add up to 39. A branch stops when its sum passes the target. What does this print?
digits = "123123"
target = 39
def ways(pos, left):
if pos == len(digits):
return 1 if left == 0 else 0
if digits[pos] == "0":
return 0
count, value = 0, 0
for end in range(pos, len(digits)):
value = value * 10 + int(digits[end])
if value > left:
break
count += ways(end + 1, left - value)
return count
print(ways(0, target))The move has three parts, and the table shows how each problem uses them.
First, build the split one piece at a time, in a fixed order. Second, reject a piece the moment it cannot work, before any deeper call. Third, remove branches that repeat the same state.
| Problem | The rejection | The repeat that is removed |
|---|---|---|
| Split a string into valid sums | a leading zero, or a sum above the target | none: each cut is different |
| Split into palindromes | a piece that is not a palindrome | none, but the page stops the search |
| Matchsticks into a square | a side with too little room | a side whose room equals one already tried |
| Partition into k equal groups | a payout that overflows the batch | a set of used payouts that failed once |
The pieces chosen so far are all valid and cover exactly the part of the input already used. A branch ends as soon as no completion can exist, and two branches that leave the same items unused are the same branch.
A rejection is safe only if it is monotone. A piece above the target stays above it, and so does every longer piece, so the loop can stop. A piece that is not a palindrome says nothing about a longer piece, so only that piece is skipped.
A piece above the target ends the loop, because every longer piece is larger. Reject at the first sign, before a deeper call.
Exercise · Find the bug: A cut that stops short. A cut splits the digits into pieces from left to right, and no piece starts with 0. This counts the cuts whose pieces add up to the target. Which line is wrong?
def ways_to_split(digits, target):
def ways(pos, left):
if pos == len(digits):
return 1
if digits[pos] == "0":
return 0
count, value = 0, 0
for end in range(pos, len(digits)):
value = value * 10 + int(digits[end])
if value > left:
break
count += ways(end + 1, left - value)
return count
return ways(0, target)The Academy lessons Backtracking with pruning and Subsets and permutations teach choose, explore and undo. Memoisation teaser shows why remembering a result saves calls. This street changes three things.
The prune is monotone. For a 16-digit string and a target of 2,000, stopping when a piece passes what is left makes 25,094 calls. Without the stop it makes 65,536.
A page needs no full list. A text of 20 equal letters has 524,288 palindromic splits. A page of 50 splits starting at position 20,000 completes only 20,050 splits, because the search stops when the page is full.
Equal branches are removed. On the 11 strips 8, 2, 7, 3, 4, 2, 8, 1, 2, 8 and 7, the search for the best frame makes 86,713 calls with no help. Longest strip first brings it to 77, skipping a side whose room equals one already tried brings it to 3,445, and doing both brings it to 17.
Remembering a failure also helps. For 14 payouts the search for equal batches makes 2,164 calls, and with a memory of failed sets of used payouts it makes 293.
Two sides with equal room give the same outcome. Try the strip on one of them, and skip the rest.
Exercise · Break it: Divisible is not enough. This returns the largest number of batches with equal totals. It returns the largest count that divides the total, and never tries to fill the batches. Find an input where it gives the wrong answer.
def most_equal_batches(amounts):
total = sum(amounts)
for k in range(len(amounts), 0, -1):
if total % k == 0:
return k
return 1Solve them in this order. The first counts cuts, the second returns a page, the third packs four sides, and the fourth remembers failed sets.
Before you code each problem, write two lines: when a piece is rejected, and which branches repeat. If the second line is "none", the page or the count must keep the search short.
Give each problem about 25 minutes. Spend the first four on the two lines, and say them aloud as you would to an interviewer. Then write the answer for an input that cannot be split.
Three edge cases return on every rung. A piece of length one is always a candidate. An empty list or a single item needs its own answer. A total that does not divide by the number of groups ends the search before it starts.
When a solution fails, check the base case before the loop. Most wrong answers on this street come from a base case that ignores the sum, or from a prune that is not monotone.
Checkpoint · Partitions and splits
Q1/5 A piece of digits has a value above what is left to pay. Why can the loop stop, and not only skip the piece?
Answer: B
The stop is monotone: a longer piece has a larger value. A piece that is not a palindrome says nothing about longer pieces, so that rule only skips.
Q2/5 The digits are 123 and the target is 7. The only full cut under 7 is 1+2+3. What must the base case return?
Answer: B
The base case must check that exactly nothing is left to pay. Using every digit is not enough.
Q3/5 On the 11 strips of the lesson, which change brought the search from 86,713 calls to 17?
Answer: B
Longest first makes overflow show early, and skipping equal rooms removes branches that repeat the same outcome. Together they give 17 calls.
Q4/5 A set of used payouts failed once to fill the remaining batches. What do you do when the search reaches the same set again?
Answer: C
Which payouts are left, and how full the current batch is, depend only on the set used. A set that failed once cannot succeed later.
Q5/5 You need only a page of 50 splits starting at position 20,000 of a list with 524,288 splits. How many splits does the lesson's search complete?
Answer: C
The search skips the splits before the page and stops when the page is full, so it completes 20,000 + 50.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.