Program to find minimum number of flips required to have alternating values in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary string s. Now suppose we can take some prefix of s and move it to the back. then, find the minimum number of characters that need to be flipped such that there will be no consecutive characters of the same value.

So, if the input is like s = "10010101111", then the output will be 2, as we can take prefix "10", then move it to back so string is "01010111110" then flip 3rd and 5th bit from right to 0 ("01010101010").

To solve this, we will follow these steps −

  • ans := size of S

  • N := size of S

  • s := 0

  • for i in range 0 to 2 * N, do

    • s := s + integer of (S[i mod N] XOR (i AND 1))

    • if i >= N - 1, then

      • ans := minimum of ans, s and N - s

      • s := s - integer of (S[(i -(N - 1)) mod N]) XOR ((i - (N - 1)) AND 1)

  • return ans

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def solve(self, S):
      ans = N = len(S)
      s = 0
      for i in range(2 * N):
         s += int(S[i % N]) ^ (i & 1)
         if i >= N - 1:
            ans = min(ans, s, N - s)
            s -= int(S[(i - (N - 1)) % N]) ^ ((i - (N - 1)) & 1)
      return ans
ob = Solution()
s = "10010101111"
print(ob.solve(s))

Input

"10010101111"

Output

2
raja
Published on 22-Dec-2020 06:21:37
Advertisements