Restore The Array Problem
Description
LeetCode Problem 1416.
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: s = "1000", k = 10000
Output: 1
Explanation: The only possible array is [1000]
Example 2:
Input: s = "1000", k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
Example 3:
Input: s = "1317", k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
Constraints:
1 <= s.length <= 10^5sconsists of only digits and does not contain leading zeros.1 <= k <= 10^9
Solution
Approach: Dynamic Programming Over Suffixes
Let f[i] be the number of ways to split the suffix s[i:] into numbers in [1, k] without leading zeros. The empty suffix has one way (f[n] = 1), and the answer is f[0].
To compute f[i], choose where the first number ends:
- If
s[i]is'0', no number can start here, sof[i] = 0. This is the case that makes splits like"1000"withk = 10impossible. - Otherwise, grow the number
x = s[i..j]one digit at a time. Whilex <= k, the rest can be split inf[j + 1]ways, so addf[j + 1]. As soon asx > k, stop: adding digits only makes it larger.
Since k <= 10^9, a valid number has at most 10 digits, so the inner loop runs at most about 10 times. Keep x in a 64-bit integer (it can briefly reach eleven digits before the check) and take every sum modulo 10^9 + 7.
Complexity: O(n · d) time, where d <= 10 is the number of digits of k, and O(n) space for f.
class Solution:
def numberOfArrays(self, s: str, k: int) -> int:
mod = 10**9 + 7
n = len(s)
f = [0] * (n + 1) # f[i] = ways to split s[i:]
f[n] = 1
for i in range(n - 1, -1, -1):
if s[i] == "0":
continue # no number can start with a zero
x = 0
for j in range(i, n):
x = x * 10 + int(s[j])
if x > k:
break # at most 10 digits before this happens
f[i] += f[j + 1]
f[i] %= mod
return f[0]