Suppose we are given a binary string input_str that contains 0s and 1s. Our task is to group the 0s and 1 by swapping the 1s in the given string. We have to perform a minimum number of swap operations, and we have to return that value. One thing to be kept in mind, we can swap the adjacent values only.
So, if the input is like input_str = 10110101, then the output will be 4
The swap will be like following −
The total number of swaps: 4.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(input_string): one = [i for i in range(len(input_string)) if input_string[i] == "1"] mid = len(one) // 2 res = 0 for i in range(len(one)): res += abs(one[mid] - one[i]) - abs(mid - i) return 0 if res < 0 else res print(solve('10110101'))