← Salesforce Interview Insights
My first instinct was just DP from left to right, define dp[i] as the number of valid splits for the first i characters, and for each position try all possible last segments.
Use dynamic programming where dp[i] represents the number of valid ways to split the prefix ending at index i. For each i, iterate over all possible start indices j < i, check if the substring s[j..i-1] is a prime number (no leading zeros, value prime), and if so, add dp[j] to dp[i]. Precompute primes up to the maximum possible value (length of string) using a sieve to allow O(1) primality checks.
Pro tip: Mention that you can optimize the inner loop by limiting the substring length to the number of digits of the maximum prime (e.g., 6 digits for 1e6), and discuss trade-offs between precomputing primes versus checking on the fly. Also, handle modulo operations carefully to avoid overflow.
Ask about the maximum length of the string, whether the string can be empty, and confirm that segments cannot have leading zeros. This determines the feasible maximum prime value and the DP table size.
Let dp[i] be the number of ways to split the prefix s[0..i-1]. Initialize dp[0] = 1. For each i from 1 to n, iterate j from 0 to i-1, and if s[j..i-1] is a valid prime, add dp[j] to dp[i] modulo 1e9+7.
Precompute all primes up to the maximum possible value (e.g., 10^6 if string length ≤ 6) using the Sieve of Eratosthenes. Then, for each substring, convert to integer (avoiding leading zeros) and check primality in O(1).
Limit the substring length to the number of digits of the maximum prime (e.g., 6). Also, skip substrings with leading zeros. This reduces time complexity from O(n^2) to O(n * L) where L is max digits.
Return dp[n] modulo 1e9+7. Analyze time complexity: O(n * L) for DP plus O(M log log M) for sieve, where M is max prime value. Space complexity: O(n + M).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.