
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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 count substrings with all 1s in binary string in Python
- Minimum Swaps required to group all 1’s together in C++
- Program to find minimum number of monotonous string groups in Python
- Minimum swaps required to make a binary string alternating in C++
- Program to find number of substrings with only 1s using Python
- Program to find minimum swaps to arrange a binary grid using Python
- Program to find minimum adjacent swaps for K consecutive ones in Python
- Program to find number of swaps required to sort the sequence in python
- Program to count number of square submatix of 1s in the given matrix in C++

Advertisements