![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Advertisements