Prime Segment Partitions of a Digit Sequence
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Count the ways to cut a digit string into prime-valued pieces without leading zeros, using prefix dynamic programming plus a fast primality check, modulo 1,000,000,007.
Prime Segment Partitions of a Digit Sequence
You are given a string digits made up only of the characters '0' to '9'.
A cut plan divides digits into one or more non-empty, consecutive pieces that, placed side by side in order, give back the original string. A cut plan is acceptable when every piece satisfies all of the following:
- Its first character is not
'0'(so"7"is allowed, but"07"is not). - The integer it represents is a prime number.
- The integer it represents is at most
10^9.
Count the acceptable cut plans for digits. Two plans are different if they cut at different positions. Because the count can be huge, return it modulo 1_000_000_007.
If no acceptable plan exists, return 0.
Notes
0and1are not prime, so pieces such as"0"or"1"are never allowed.- A piece longer than 9 digits is never allowed, because it would exceed
10^9. - A zero in the middle or at the end of a piece is fine, as in
"307". Only a leading zero is forbidden.
Constraints
1 <= len(digits) <= 1000digitscontains only the characters'0'through'9'.- The function returns an integer in the range
[0, 1_000_000_006].
Examples
Example 1
Input: count_prime_cuts('113')
Output: 2
Example 2
Input: count_prime_cuts('3175')
Output: 3
Example 3
Input: count_prime_cuts('023')
Output: 0
Hints
Hint 1
Let ways[i] be the number of acceptable plans for the first i characters, with ways[0] = 1 for the empty prefix. How can the last piece of a plan help you compute ways[i]?
Hint 2
Every acceptable piece is a prime no larger than 10^9, and 10^9 itself is not prime, so no piece has more than 9 digits. From each start position you only need to test at most 9 end positions.
Hint 3
Skip any start position whose character is '0'. Test each candidate value for primality (trial division up to the square root, or Miller-Rabin, with optional caching), and take the modulus at every addition.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a prefix-counting dynamic program, the same shape as "Decode Ways".
Let ways[i] be the number of acceptable cut plans for the first i characters. The empty prefix has exactly one plan, so ways[0] = 1. The answer is ways[n].
Every plan for a prefix is determined by its last piece together with a plan for the part before that piece. So ways[end + 1] is the sum of ways[start] over every start for which digits[start:end + 1] is an allowed piece.
The code pushes values forward. For each start:
- Skip it if
ways[start] == 0(nothing to propagate) or ifdigits[start] == '0'(no piece may begin with zero). - Extend
endfromstartup to at moststart + 8, building the integer incrementally withvalue = value * 10 + digit. - Whenever
valueis prime, addways[start]toways[end + 1], modulo1_000_000_007.
Only 9 digits need to be considered because any 10-digit number is at least 10^9, and 10^9 is composite. So no allowed piece is longer than 9 digits.
For primality, the code trial-divides by the primes up to 37, which settles most composites and recognizes those small primes. It then runs Miller-Rabin with bases 2, 3, 5, 7, 11, which is deterministic for all values below about 2.15 * 10^12 and so covers everything up to 10^9.
Why it is correct
- Each plan is counted once: it has a unique last piece, and the remainder is a plan for a shorter prefix.
- When index
startis processed,ways[start]is already final because all its contributions come from smaller indices. - Skipping a start with a leading
'0'enforces the no-leading-zero rule, and0and1are rejected by the primality test. - Skipping starts where
ways[start] == 0changes nothing since they would add zero. - The 9-digit limit loses no valid pieces, as argued above.
Complexity
- Time: at most 9 primality tests per start index, so about 9n tests, each costing a handful of modular exponentiations on numbers up to
10^9. That is effectively linear inn. - Space: O(n) for the
waysarray.
Reference solution
MOD = 1_000_000_007
def _is_prime(n):
if n < 2:
return False
small_primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
for p in small_primes:
if n % p == 0:
return n == p
# These bases are deterministic for all n < 2**32, including 10**9.
d = n - 1
r = 0
while d % 2 == 0:
d //= 2
r += 1
for a in (2, 3, 5, 7, 11):
if a >= n:
continue
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = x * x % n
if x == n - 1:
break
else:
return False
return True
def count_prime_cuts(digits):
n = len(digits)
ways = [0] * (n + 1)
ways[0] = 1
for start in range(n):
if ways[start] == 0 or digits[start] == '0':
continue
value = 0
for end in range(start, min(n, start + 9)):
value = value * 10 + ord(digits[end]) - 48
if _is_prime(value):
ways[end + 1] = (ways[end + 1] + ways[start]) % MOD
return ways[n]