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 modulo109 + 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.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"1000"
10000
Example 2
"1000"
10
Example 3
"1317"
2000
Related Problems
Number of Ways to Separate Numbers (number-of-ways-to-separate-numbers)
Number of Beautiful Partitions (number-of-beautiful-partitions)
Step 02
Core Insight
What unlocks the optimal approach
Use dynamic programming. Build an array dp where dp[i] is the number of ways you can divide the string starting from index i to the end.
Keep in mind that the answer is modulo 10^9 + 7 and take the mod for each operation.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1416: Restore The Array
// Auto-generated Java example from py.
class Solution {
public void exampleSolution() {
}
}
// Reference (py):
// # Accepted solution for LeetCode #1416: Restore The Array
// # Time: O(nlogk)
// # Space: O(logk)
//
// class Solution(object):
// def numberOfArrays(self, s, k):
// """
// :type s: str
// :type k: int
// :rtype: int
// """
// MOD = 10**9 + 7
// klen = len(str(k))
// dp = [0]*(klen+1)
// dp[len(s)%len(dp)] = 1
// for i in reversed(xrange(len(s))):
// dp[i%len(dp)] = 0
// if s[i] == '0':
// continue
// curr = 0
// for j in xrange(i, min(i+klen, len(s))):
// curr = 10*curr + int(s[j])
// if curr > k:
// break
// dp[i%len(dp)] = (dp[i%len(dp)] + dp[(j+1)%len(dp)])%MOD
// return dp[0]
// Accepted solution for LeetCode #1416: Restore The Array
// Auto-generated Go example from py.
func exampleSolution() {
}
// Reference (py):
// # Accepted solution for LeetCode #1416: Restore The Array
// # Time: O(nlogk)
// # Space: O(logk)
//
// class Solution(object):
// def numberOfArrays(self, s, k):
// """
// :type s: str
// :type k: int
// :rtype: int
// """
// MOD = 10**9 + 7
// klen = len(str(k))
// dp = [0]*(klen+1)
// dp[len(s)%len(dp)] = 1
// for i in reversed(xrange(len(s))):
// dp[i%len(dp)] = 0
// if s[i] == '0':
// continue
// curr = 0
// for j in xrange(i, min(i+klen, len(s))):
// curr = 10*curr + int(s[j])
// if curr > k:
// break
// dp[i%len(dp)] = (dp[i%len(dp)] + dp[(j+1)%len(dp)])%MOD
// return dp[0]
# Accepted solution for LeetCode #1416: Restore The Array
# Time: O(nlogk)
# Space: O(logk)
class Solution(object):
def numberOfArrays(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
MOD = 10**9 + 7
klen = len(str(k))
dp = [0]*(klen+1)
dp[len(s)%len(dp)] = 1
for i in reversed(xrange(len(s))):
dp[i%len(dp)] = 0
if s[i] == '0':
continue
curr = 0
for j in xrange(i, min(i+klen, len(s))):
curr = 10*curr + int(s[j])
if curr > k:
break
dp[i%len(dp)] = (dp[i%len(dp)] + dp[(j+1)%len(dp)])%MOD
return dp[0]
// Accepted solution for LeetCode #1416: Restore The Array
/**
* [1416] Restore The Array
*
* 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^5
* s consists of only digits and does not contain leading zeros.
* 1 <= k <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/restore-the-array/
// discuss: https://leetcode.com/problems/restore-the-array/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn number_of_arrays(s: String, k: i32) -> i32 {
const MOD: i32 = 1_000_000_007;
let n = s.len();
let k_10 = k / 10;
let mut dp = vec![0; n + 1];
dp[n] = 1;
let bytes = s.as_bytes();
for (i, c) in bytes.iter().copied().enumerate().rev() {
let mut num_ways = 0;
if c != b'0' {
let mut num = 0;
for idx in i..n {
if num <= k_10 {
let d = (bytes[idx] - b'0') as i32;
num = num * 10 + d;
if num <= k {
num_ways = (num_ways + dp[idx + 1]) % MOD;
continue;
}
}
break;
}
}
dp[i] = num_ways;
}
dp[0]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1416_example_1() {
let s = "1000".to_string();
let k = 10000;
let result = 1;
assert_eq!(Solution::number_of_arrays(s, k), result);
}
#[test]
fn test_1416_example_2() {
let s = "1000".to_string();
let k = 10;
let result = 0;
assert_eq!(Solution::number_of_arrays(s, k), result);
}
#[test]
fn test_1416_example_3() {
let s = "1317".to_string();
let k = 2000;
let result = 8;
assert_eq!(Solution::number_of_arrays(s, k), result);
}
}
// Accepted solution for LeetCode #1416: Restore The Array
// Auto-generated TypeScript example from py.
function exampleSolution(): void {
}
// Reference (py):
// # Accepted solution for LeetCode #1416: Restore The Array
// # Time: O(nlogk)
// # Space: O(logk)
//
// class Solution(object):
// def numberOfArrays(self, s, k):
// """
// :type s: str
// :type k: int
// :rtype: int
// """
// MOD = 10**9 + 7
// klen = len(str(k))
// dp = [0]*(klen+1)
// dp[len(s)%len(dp)] = 1
// for i in reversed(xrange(len(s))):
// dp[i%len(dp)] = 0
// if s[i] == '0':
// continue
// curr = 0
// for j in xrange(i, min(i+klen, len(s))):
// curr = 10*curr + int(s[j])
// if curr > k:
// break
// dp[i%len(dp)] = (dp[i%len(dp)] + dp[(j+1)%len(dp)])%MOD
// return dp[0]
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.