Restore The Array - Problem

A program was supposed to print an array of integers. Due to a bug, the program forgot to print whitespaces and the array is printed as a string of digits s.

All we know is that:

  • All integers in the original array were in the range [1, k]
  • There are no leading zeros in any of the integers

Given the string s and the integer k, return the number of possible arrays that can be printed as s using the mentioned program.

Note: Since the answer may be very large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: s = "1317", k = 2000
Output: 8
💡 Note: Possible arrays: [1,3,1,7], [1,3,17], [1,31,7], [1,317], [13,1,7], [13,17], [131,7], [1317]. All numbers are ≤ 2000.
Example 2 — Small k
$ Input: s = "2020", k = 30
Output: 1
💡 Note: Only possible array is [20,20]. Cannot take "2020" or "202" as they exceed k=30.
Example 3 — Leading Zero
$ Input: s = "1012", k = 50
Output: 2
💡 Note: Possible arrays: [1,0,1,2] is invalid (0 not in range [1,k]), [10,12] and [1,0,12] are invalid, only [10,1,2] and [1,012] but 012 has leading zero, so only [10,1,2] is valid. Actually [1,12] is also valid, so answer is 2: [10,1,2] and [1,12].

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only digits
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Restore The Array - Dynamic Programming INPUT String s (no spaces): 1 3 1 7 s = "1317" Range limit: k = 2000 Possible array splits: [1,3,1,7] [1,3,17] [1,31,7] [1,317] [13,1,7] [13,17] [131,7] [1317] All values in [1, 2000] ALGORITHM STEPS 1 Define DP State dp[i] = ways to split s[i:] 2 Base Case dp[n] = 1 (empty suffix) 3 Transition Try all valid nums at i 4 Accumulate Sum dp[j] for valid j DP Table (right to left): i=4 i=3 i=2 i=1 i=0 1 1 2 3 8 dp[0] = 8 valid arrays MOD = 10^9 + 7 FINAL RESULT Number of Arrays: 8 All 8 Valid Arrays: 1. [1, 3, 1, 7] 2. [1, 3, 17] 3. [1, 31, 7] 4. [1, 317] 5. [13, 1, 7] 6. [13, 17] 7. [131, 7] 8. [1317] OK - All in range [1, 2000] Key Insight: At each position i, try forming numbers with 1, 2, 3... digits. A number is valid if: (1) no leading zero, (2) value is between 1 and k. For each valid number ending at j, add dp[j+1] to dp[i]. Time: O(n * log k) since we check at most log10(k) digits at each position. Space: O(n) for the DP array. TutorialsPoint - Restore The Array | Dynamic Programming Approach
Asked in
Google 25 Amazon 18 Facebook 15
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen