Given a binary stringS consisting of 0’s and 1’s, The task is to find the minimum number of flips required to generate a binary string of all ones. The flip is performed on either two or threeadjacent indices.
Input: S = “0010” Output: 2 Explanation: Operations performed are: 0010 -> 0001 -> 1111
Input: S = “0011110” Output: 3 Explanation: Operations performed are: 0011110 -> 1111110 -> 1111000 -> 1111111
Approach: The basic idea to solve this problem is to perform flips on the first2 or 3 characters and add the result of recursion with the next positions. It’s just a recursive brute forcing of all possibilities. For every index of the string, try two adjacent flips and three adjacent flips and then recurse on that subproblem. One important thing is that the result is independent of the order of the flips. Follow the below steps to solve the problem:
If the given string doesn’t consist of any zeros then return “0” and if there are only “1’s” then no flip is needed.
If the given string, at any moment becomes equal to “00” or “000” then return “1” as only 1 flip is needed to make it all ones.
We need a list for storing and comparing minimum possibilities at any moment of the recursive call.
If the string starts with “0” and the length of the string is greater than 2 or 3 then we flip the first two or first three characters and recursively call again for the next index.
If strings start with “1“, we remove it by recursively calling it for the rest of the part.
Now in the case of “1“, if “0” is present at the first two or three positions then we flip the first two or three positions and recursively call for the rest of the part along with appending/adding results to the lists.
Once a cycle is completed we return the minimum of all the elements stored in the list.
Below is the implementation of the above approach:
Please Login to comment...