
- 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
Minimum Swaps to Group All 1's Together in Python
Suppose we have a binary array data, we have to find the minimum number of swaps required to group all 1’s stored in the array together in any place in the array. So if the array is like [1,0,1,0,1,0,0,1,1,0,1], then the output will be 3, as possible solution is [0,0,0,0,0,1,1,1,1,1,1]
To solve this, we will follow these steps −
- set one := 0, n:= length of data array
- make an array summ of size n, and fill this with 0, set summ[0] := data[0]
- one := one + data[0]
- 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
Example(Python)
Let us see the following implementation to get better understanding −
class Solution(object): def minSwaps(self, data): one = 0 n = len(data) summ=[0 for i in range(n)] summ[0] = data[0] one += data[0] 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.minSwaps([1,0,1,0,1,0,0,1,1,0,1]))
Input
[1,0,1,0,1,0,0,1,1,0,1]
Output
3
- Related Articles
- Minimum Swaps required to group all 1’s together in C++
- 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
- Minimum swaps required to bring all elements less than or equal to k together in C++
- Program to find minimum number of swaps needed to arrange all pair of socks together in C++
- Program to group the 1s with minimum number of swaps in a given string in Python
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum adjacent swaps for K consecutive ones in Python
- Minimum Swaps to Make Strings Equal in C++
- Minimum Swaps To Make Sequences Increasing in C++
- Program to find minimum swaps to arrange a binary grid using Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Minimum swaps required to make a binary string alternating in C++
- Minimum number of swaps required to sort an array in C++
- Program to find minimum possible integer after at most k adjacent swaps on digits in Python

Advertisements