1792. Prime Digit Splits
A lock displays a long code made only of the characters '0' to '9', given as the string digits. A technician wants to cut it into consecutive pieces, every piece being a prime number written in ordinary decimal form: no leading zero, and at most 6 digits long. The pieces must cover the whole string, in order, with nothing left over.
Return the number of different ways to cut digits like this, as a long. Two ways differ when their sets of cut positions differ, even if they produce equal numbers. Return 0 when no valid cutting exists. Backtrack over the cut positions, test each candidate piece by trial division, and memoise the number of ways by starting index so each suffix is solved once. Each of the n = digits.length start positions tries at most 6 pieces of at most 1000 trial divisions, so time is O(n * 6 * 1000) and space is O(n).
Example 1
- Input:
- digits = "2357"
- Output:
- 3
- Explanation:
The valid cuttings are 2|3|5|7, 23|5|7 and the whole string 2357, so the number of ways is 3.
Example 2
- Input:
- digits = "11"
- Output:
- 1
- Explanation:
Only the single piece 11 is prime (1 alone is not), so there is 1 way.
Example 3
- Input:
- digits = "10"
- Output:
- 0
- Explanation:
Neither 1, 0 nor 10 is prime, so there are 0 ways.
Constraints
1 ≤ digits.length ≤ 40
digits contains only the characters '0' to '9'
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n * 6 * sqrt(10^6))
- Space
- O(n)