Advertisement
Iam_Sandeep

1888. Minimum Number of Flips to Make the Binary String Alternating

Jul 17th, 2022
1,210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. '''
  2. You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
  3.  
  4. Type-1: Remove the character at the start of the string s and append it to the end of the string.
  5. Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
  6. Return the minimum number of type-2 operations you need to perform such that s becomes alternating.
  7. '''
  8.  
  9. class Solution:
  10.     def minFlips(self, s: str) -> int:
  11.         n=len(s)
  12.         s=s+s
  13.         tar1,tar2='01'*n,'10'*n
  14.         a,b=0,0#a--->for unbalanced chars in tar1 simultaneously b for tar2
  15.         for i in range(n):
  16.             if tar1[i]!=s[i]:a+=1
  17.             if tar2[i]!=s[i]:b+=1
  18.         ans=float('inf')
  19.        
  20.         ans=min(ans,a,b)
  21.         for i in range(n,2*n):
  22.             if tar1[i-n]!=s[i-n]:a-=1
  23.             if tar1[i]!=s[i]:a+=1
  24.             if tar2[i-n]!=s[i-n]:b-=1
  25.             if tar2[i]!=s[i]:b+=1
  26.             ans=min(ans,a,b)
  27.         return ans
  28.            
  29.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement