Given a binary string S, the task is to find the maximum number of parts that you can split it into such that every part is divisible by 2. If the string can’t be split satisfying the given conditions then print -1.
Input: S = “100”
The splits are as follows:
“10” ans “0”.
Input: S = “110”
Approach: This problem can be solved greedily, start from the left end and put a cut at an index j such that j is the smallest index for which sub-string upto j is divisible by 2. Now, continue this step with the rest of the left-over string. It is also known that any binary number ending with a 0 is divisible by 2. Thus, put a cut after each and every zero and the answer will be equal to the number of zeros in the string. The only case where the answer is not possible is when the given string is odd i.e. no matter how cuts are made on the string, the last split part will always be odd.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.