Bank app~35 min2s · 256 MBtarget O(10 n) time, O(n) spaceclassic twin: lc-1416dp
A bank app receives account references as a stream of digits with the separators lost. Every reference is a whole number from 1 to k, written without leading zeros. The stream 1317 with k = 2000 can be split as 1, 3, 1, 7 or as 13, 17 or 131, 7 and in other ways.
Your team lead asks: "In how many ways can the stream be split into valid references?"
Write count_splits(digits, k).
digits is a string of digits, possibly with zeros. A split cuts it into pieces. Each piece is a whole number from 1 to k, written without a leading zero.0 or 07 is not valid. A piece such as 10 is valid when 10 ≤ k.1,000,000,007. If the stream cannot be split, return 0.Input: digits = "21304", k = 250
Output: 3Let ways[i] be the number of splits of the first i digits. The last id ends at digit i - 1 and has 1 to 3 digits here, because 250 has 3 digits. A piece is valid when it does not start with 0 and its value is at most k. A valid piece that starts at j adds ways[j].
| i | Digits so far | Pieces tried, shortest first | ways[i] |
|---|---|---|---|
| 0 | none | 1 | |
| 1 | 2 |
2: adds ways[0] = 1 | 1 |
| 2 | 21 |
1: adds ways[1] = 1; 21: adds ways[0] = 1 | 2 |
| 3 | 213 |
3: adds ways[2] = 2; 13: adds ways[1] = 1; 213: adds ways[0] = 1 | 4 |
| 4 | 2130 |
0: starts with 0; 30: adds ways[2] = 2; 130: adds ways[1] = 1; 2130: over 250 | 3 |
| 5 | 21304 |
4: adds ways[4] = 3; 04: starts with 0; 304: over 250 | 3 |
The answer is ways[5] = 3.
Input: digits = "1317", k = 2000
Output: 8The stream can be cut after any digit when every piece stays at most 2000. That gives 8 splits, one for each choice of the 3 cut points.
Input: digits = "0123", k = 100
Output: 0The stream starts with 0, and an id cannot start with 0. So no split exists.
1 ≤ len(digits) ≤ 100,000digits has only the characters 0 to 9.1 ≤ k ≤ 1,000,000,000, so every id has at most 10 digits.There can be 100,000 digits. Each gap between digits is a cut or not, so up to 2 to the power 99,999 splits exist, and listing them never finishes. A table with one entry for each prefix, and at most 10 pieces to try for each entry, takes about a million steps.