You are given a string ‘NUM’, the string is made up of digits (0-9),. Your task is to find the number of ways to split the string of digits into a list of non-decreasing positive integers and no integer should have leading zeros.
Note :The answer may be very large so return it modulo ‘10^9 + 7’.
For Example :
You are given ‘NUM’ = “329”, Here you can split the string as [3, 29] and [329]. Since there are 2 ways the answer will be 2.
Note that a split [32, 9] is invalid because the list is not in non-decreasing order.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first and only line of each test case contains a string ‘NUM’ representing the string given in the problem.
Output Format :
For each test case print a single integer representing the number of ways you can split the string with the given conditions.
Print a separate line for each test case.
1 <= T <= 10
1 <= NUM.size <= 500
NUM[i] is a digit from 0 to 9
Time Limit: 1 sec
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
2
329
4256
2
3
For the first test case, ‘NUM’ = “329”, Here you can split the string as [3, 29] and [329]. Since there are 2 ways to split the string the answer will be 2.
For the second test case ‘NUM’ = “4256”, Here you can split the string as [4, 256], [42, 56], [4256]. Since there are 3 ways to split the string the answer will be 3.
2
901
023
1
0
Try the naive approach to the solution
In this approach, we can see that if any string starts with a 0 then it has no was to be separated into a list of non-decreasing positive integers.
Let's imagine we know the number of ways to split characters according to the rules before each position in the string and all possible lengths of the previous part. Then for the next position, the number of ways to split characters from start to this position can be calculated recursively.
And what if we know for each position in the string number of ways to split it into parts no longer than D. Then for D +1 we can calculate it from previous values for each position.
We will create a function ‘checkString(nums, start1, start2, length)’ which will check if the number formed by starting at ‘start1’ index is less than the number formed by starting at the ‘start2’ index, where both are of ‘length’ length
Algorithm:
O( N ^ 3 ), where N is the length of the given string.
We are iterating over all the length of each digit and trying to place the comma at each position, for we check if the numbers are non decreasing which will take ~N^3.
Hence the final time complexity is O( N ^ 3 ).
O( N ), where N is the length of the given string.
We are maintaining two arrays of ~N length each.
Hence the overall time complexity O( N )