Bank app~25 min2s · 256 MBtarget O(2^n) worst case, far less with pruning time, O(n) spacebacktracking
A banking app scans a printed statement line, and the separators between the amounts are lost. All that is left is a string of digits, such as 123123.
The app knows the total that the line should add up to. An amount never has a leading zero, and it is always at least 1.
You count the ways to cut the digits into amounts that add up to the total.
Write ways_to_split(digits, target).
digits is a string of digits. Cut it into one or more pieces, from left to right, so that every digit belongs to exactly one piece.0. So 0 and 05 are not valid pieces.target.Input: digits = "123123", target = 39
Output: 3The solution chooses the first piece, then splits the rest in the same way. A branch stops as soon as the pieces so far add up to more than the target.
| First piece | Left to pay | Ways to finish |
|---|---|---|
1 |
38 | 2 |
12 |
27 | 1 |
123 |
stops, 123 is more than 39 | 0 |
The three cuts are 1+2+31+2+3, 1+23+12+3 and 12+3+1+23. Each adds up to 39.
Input: digits = "123123", target = 12
Output: 1Only the cut 1+2+3+1+2+3 adds up to 12. Joining any two neighbouring digits gives a piece of 10 or more, and the total becomes too big.
Input: digits = "205", target = 7
Output: 0The cut 2+05 adds up to 7, but the piece 05 starts with a zero. The cuts 20+5 and 205 add up to 25 and 205, so the answer is 0.
1 ≤ len(digits) ≤ 22, and every character is a digit from 0 to 91 ≤ target ≤ 1,000,000,000A string of 22 digits has 21 places where it can be cut, and each place is cut or not. That gives 2 to the power of 21, which is 2,097,152 cuts to try at most. Every cut can be checked, but stopping a branch early makes the search much smaller.