Suppose we have a binary string, and we can swap any two bits. We have to find the minimum number of swaps required to group all 1s together.
So, if the input is like s = "0111001", then the output will be 1, as We can perform these swaps: 0111001 -> 1111000.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def solve(self, s): data = list(map(int, list(s))) one = 0 n = len(data) summ=[0 for i in range(n)] summ = data one += data for i in range(1,n): summ[i] += summ[i-1]+data[i] one += data[i] ans = one left = 0 right = one-1 while right <n: if left == 0: temp = summ[right] else: temp = summ[right] - summ[left-1] ans = min(ans,one-temp) right+=1 left+=1 return ans ob = Solution() s = "0111001" print(ob.solve(s))