You are given a string ‘S’ of size ‘N’ where ’S’ contains only characters ‘0’ and ‘1’. Your task is to divide ‘S’ into ‘K’ contiguous substrings such that the following conditions hold true :
1. Let ‘X’ be a binary number formed by reading a substring of ‘S’ from left to right.
2. ‘X’ must not contain leading zeroes.
3. The decimal equivalent of ‘X’ must be a power of 5.
4. K must be the minimum possible.
Note :
If no such ‘K’ possible, then you need to return -1.
The first line of input contains an integer 'T' representing the number of test cases.
The first and the only line of each test case contains a single string, ‘S’.
Output Format :
For each test case, print the minimum possible value of K. If no such ‘K’ possible, then you need to print -1.
The output of each test case will be printed in a separate line.
1 <= T <= 5
1 <= N <= 100
‘S’ contains only characters ‘0’ and ‘1’.
Where ‘T’ is the number of test cases, ‘N’ is the length of the given string.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
2
1
101
1
1
Test Case 1 :
Given S = “1”,
1 in base 10 = 1
1 = 5 ^ 0
So, minimum value of K = 1.
Test Case 2 :
Given S = “101”,
“101” in base 10 = 5
5 = 5 ^ 1
So, minimum value of K = 1.
2
111
110
3
-1
Test Case 1 :
Given S = “111”
We can make three partitions of ‘S’ as “1” + “1” + “1”
1 in base 10 = 1
1 = 5 ^ 0
So minimum value of K = 3.
Test Case 2 :
Given S = “110”
There is no valid partition of this substring, So we need to print -1.
Can you check all possible partitions ?
The idea here is to check all possible partitions. For each index ‘i’ if substring from index ‘i’ to some index ‘j’ is a power of 5 then we will have two options either make a partition from the index or not. So, we will try both of these options and choose the one that gives us the minimum result.
Algorithm:
Description of ‘partition’ function
This function will take two parameters :
int partition(index, S) :
Description of ‘isPowerFive’ function
This function will take one parameter :
bool isPowerFive( S ) :
O(N ^ N), where ‘N’ is the length of the string.
In the worst case we need to check all possible partitions which are O(N ^ N) as for each index in the current recursive stack we are making O(N) recursive calls. Our ‘isPowerFive’ is taking O(N) time as we are running a single loop to calculate it. So overall time complexity will be O(N ^ N) + O(N) = O(N ^ N)
O(N), where ‘N’ is the length of the string.
Our ‘partition’ function requires O(N) space in the form of recursive stack space. Hence, the overall space complexity is O(N).