Number of Ways to Separate Numbers Problem
Description
LeetCode Problem 1977.
You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 10^9 + 7.
Example 1:
Input: num = "327"
Output: 2
Explanation: You could have written down the numbers:
3, 27
327
Example 2:
Input: num = "094"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Example 3:
Input: num = "0"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Constraints:
1 <= num.length <= 3500numconsists of digits'0'through'9'.
Solution
Approach: Dynamic Programming + Prefix Sums + LCP
Let dp[i][j] be the number of ways to split the first i digits so that the last number has length j. Start with dp[0][0] = 1; the answer is the sum of dp[n][j] over all j.
For the last number occupying num[i-j..i) (it must not start with 0), the previous number ends at i - j. Previous numbers shorter than j are always smaller, so their counts can be added at once with a prefix sum over the length. A previous number of the same length j is allowed only if it is not larger, which we compare in O(1) using a table of longest common prefixes of suffixes, built in O(n^2).
Complexity: time O(n^2), space O(n^2), where n is the length of num.
class Solution:
def numberOfCombinations(self, num: str) -> int:
def cmp(i, j, k):
x = lcp[i][j]
return x >= k or num[i + x] >= num[j + x]
mod = 10**9 + 7
n = len(num)
lcp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(n - 1, -1, -1):
if num[i] == num[j]:
lcp[i][j] = 1 + lcp[i + 1][j + 1]
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
v = 0
if num[i - j] != '0':
if i - j - j >= 0 and cmp(i - j, i - j - j, j):
v = dp[i - j][j]
else:
v = dp[i - j][min(j - 1, i - j)]
dp[i][j] = (dp[i][j - 1] + v) % mod
return dp[n][n]