- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to group the 1s with minimum number of swaps in a given string in Python

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 −

10110101->01110101->01111001->01111010->01111100

The total number of swaps: 4.

To solve this, we will follow these steps −

- one := a new list containing the positions in input_str where the 1s are located
- mid := floor value of (size of one / 2)
- res := 0
- for i in range 0 to size of one, do
- res := res + |one[mid] - one[i]| - |mid - i|

- if res < 0, then
- return 0

- otherwise,
- return res

## Example

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'))

## Input

'10110101'

## Output

4

- Related Questions & Answers
- Program to find minimum swaps needed to group all 1s together in Python
- Program to count number of swaps required to group all 1s together in Python
- Program to find minimum swaps required to make given anagram in python
- Minimum Swaps to Group All 1's Together in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to determine the minimum cost to build a given string in python
- Program to find number of substrings with only 1s using Python
- Program to count number of square submatix of 1s in the given matrix in C++
- Program to find number of swaps required to sort the sequence in python
- Program to find minimum number of monotonous string groups in Python
- Minimum number of swaps required to sort an array in C++
- Minimum swaps required to make a binary string alternating in C++
- Program to find minimum swaps to arrange a binary grid using Python
- Minimum Swaps required to group all 1’s together in C++
- Program to count substrings with all 1s in binary string in Python

Advertisements