# Program to find minimum swaps needed to group all 1s together in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a binary string, we have to find the minimum number of swaps needed to group all 1’s together in any place in the string. So if the input is like "10101001101", then the output will be 3, as possible solution is "00000111111".

To solve this, we will follow these steps −

• data := a list of bits from the given string

• set one := 0, n:= length of data array

• make an array summ of size n, and fill this with 0, set summ := data

• one := one + data

• for i in range 1 to n – 1

• summ[i] := summ[i - 1] + data[i]

• one := one + data[i]

• ans := one

• left := 0, right := one – 1

• while right < n

• if left is 0, then temp := summ[right], otherwise temp := summ[right] –

• summ[left - 1]
• ans := minimum of ans, one – temp

• increase right and left by 1

• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution(object):
def solve(self, data):
data = list(map(int, list(data)))
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()
print(ob.solve("10101001101"))

## Input

"10101001101"

## Output

3