Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
- Type-1: Remove the character at the start of the string s and append it to the end of the string.
- Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
- Return the minimum number of type-2 operations you need to perform such that s becomes alternating.
- '''
- class Solution:
- def minFlips(self, s: str) -> int:
- n=len(s)
- s=s+s
- tar1,tar2='01'*n,'10'*n
- a,b=0,0#a--->for unbalanced chars in tar1 simultaneously b for tar2
- for i in range(n):
- if tar1[i]!=s[i]:a+=1
- if tar2[i]!=s[i]:b+=1
- ans=float('inf')
- ans=min(ans,a,b)
- for i in range(n,2*n):
- if tar1[i-n]!=s[i-n]:a-=1
- if tar1[i]!=s[i]:a+=1
- if tar2[i-n]!=s[i-n]:b-=1
- if tar2[i]!=s[i]:b+=1
- ans=min(ans,a,b)
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement