# 1416. Restore The Array ###### tags: `leetcode` ## Description 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 109 + 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 <= 105 s consists of only digits and does not contain leading zeros. 1 <= k <= 109 ## Solution - The problem can be solved by using dynamic programming, keeping the substring count for each iteration - In order to fasten up, get the degree for the `k` and for each time, we can add up the value in the degree without checking the availability - If the substring starts with `0`, the answer for the substring should be 0 ```cpp= if (s[i] == '0') dp[i] = 0; ``` - Add for all the value that is inside the degree range ```cpp= for (int j = 1; j < kVal && i + j < s.length(); j++) dp[i] = (dp[i] + dp[i + j]) % 1000000007; ``` - For the one that is just met, calculate the value and do the comparison. For the whole string, the combination would be 1 ```cpp= if (i + kVal < s.length()) { if (stol(s.substr(i, kVal)) <= k) dp[i] = (dp[i] + dp[i + kVal]) % 1000000007; } else if (stol(s.substr(i)) <= k) dp[i]++; ```