Minimum adjacent swaps required to Sort Binary array (original) (raw)
Last Updated : 29 Apr, 2025
Given a binary array, the task is to find the **minimum number of **swaps needed to sort this binary array. We are allowed to swap only adjacent elements.
**Examples:
**Input : arr[] = [0, 0, 1, 0, 1, 0, 1, 1]
**Output : 3
**Explanation:
1st swap : [0, 0, 1, 0, 0, 1, 1, 1]
2nd swap : [0, 0, 0, 1, 0, 1, 1, 1]
3rd swap : [0, 0, 0, 0, 1, 1, 1, 1]**Input : arr[]= [0, 0, 0, 1, 1]
**Output : 0
**Explanation: Array is already sorted.
**Approach:
Since a sorted binary array would have all 0s followed by all 1s, we can process the array from right to left and calculate how many positions each 1 needs to travel through to reach its correct position. The count of positions for a 1 would be equal to number of zeros on right side of it.
Step by step approach:
- Start traversing the array from the end:
- If 0 is found, increment the zero count.
- When a 1 is found, it must move past all zeros to its right. So, add the count of zeros to the total swaps for each 1 encountered.
**Illustration:
Taking example of arr[] = [0, 0, 1, 0, 1, 0, 1, 1]:
- Position 7: Element is 1, zero count = 0, swaps = 0
- Position 6: Element is 1, zero count = 0, swaps = 0
- Position 5: Element is 0, zero count = 1, swaps = 0
- Position 4: Element is 1, zero count = 1, swaps = 1
- Position 3: Element is 0, zero count = 2, swaps = 1
- Position 2: Element is 1, zero count = 2, swaps = 3
- Position 1: Element is 0, zero count = 3, swaps = 3
- Position 0: Element is 0, zero count = 4, swaps = 3 + 0 = 3
C++ `
// C++ program to find Minimum adjacent // swaps required to Sort Binary array #include <bits/stdc++.h> using namespace std;
// Function to find Minimum adjacent // swaps required to Sort Binary array int minSwaps(vector &arr) { int n = arr.size(); int res = 0;
int zeroCount = 0;
for (int i = n - 1; i >= 0; i--) {
// If current element is 0,
// increment count of zeros
if (arr[i] == 0) {
zeroCount++;
}
// If current element is 1, it needs to be
// swapped with the number of zeros found
// so far.
else {
res += zeroCount;
}
}
return res;
}
int main() { vector arr = {0, 0, 1, 0, 1, 0, 1, 1}; cout << minSwaps(arr); return 0; }
Java
// Java program to find Minimum adjacent // swaps required to Sort Binary array import java.util.*;
class GfG {
// Function to find Minimum adjacent
// swaps required to Sort Binary array
static int minSwaps(int[] arr) {
int n = arr.length;
int res = 0;
int zeroCount = 0;
for (int i = n - 1; i >= 0; i--) {
// If current element is 0,
// increment count of zeros
if (arr[i] == 0) {
zeroCount++;
}
// If current element is 1, it needs to be
// swapped with the number of zeros found
// so far.
else {
res += zeroCount;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {0, 0, 1, 0, 1, 0, 1, 1};
System.out.println(minSwaps(arr));
}
}
Python
Python program to find Minimum adjacent
swaps required to Sort Binary array
Function to find Minimum adjacent
swaps required to Sort Binary array
def minSwaps(arr): n = len(arr) res = 0
zeroCount = 0
for i in range(n - 1, -1, -1):
# If current element is 0,
# increment count of zeros
if arr[i] == 0:
zeroCount += 1
# If current element is 1, it needs to be
# swapped with the number of zeros found
# so far.
else:
res += zeroCount
return res
if name == "main": arr = [0, 0, 1, 0, 1, 0, 1, 1] print(minSwaps(arr))
C#
// C# program to find Minimum adjacent // swaps required to Sort Binary array using System;
class GfG {
// Function to find Minimum adjacent
// swaps required to Sort Binary array
static int minSwaps(int[] arr) {
int n = arr.Length;
int res = 0;
int zeroCount = 0;
for (int i = n - 1; i >= 0; i--) {
// If current element is 0,
// increment count of zeros
if (arr[i] == 0) {
zeroCount++;
}
// If current element is 1, it needs to be
// swapped with the number of zeros found
// so far.
else {
res += zeroCount;
}
}
return res;
}
static void Main(string[] args) {
int[] arr = {0, 0, 1, 0, 1, 0, 1, 1};
Console.WriteLine(minSwaps(arr));
}
}
JavaScript
// JavaScript program to find Minimum adjacent // swaps required to Sort Binary array
// Function to find Minimum adjacent // swaps required to Sort Binary array function minSwaps(arr) { let n = arr.length; let res = 0;
let zeroCount = 0;
for (let i = n - 1; i >= 0; i--) {
// If current element is 0,
// increment count of zeros
if (arr[i] == 0) {
zeroCount++;
}
// If current element is 1, it needs to be
// swapped with the number of zeros found
// so far.
else {
res += zeroCount;
}
}
return res;
}
let arr = [0, 0, 1, 0, 1, 0, 1, 1]; console.log(minSwaps(arr));
`
**Time Complexity: O(n)
**Auxiliary Space: O(1)
Now try the below question yourself
What would be the count when we can swap any 0 with any 1?
Similar Reads
- Minimum adjacent swaps required to make a binary string alternating Given a binary string S of size N, the task is to find the number of minimum adjacent swaps required to make the string alternate. If it is not possible to do so, then print -1. Examples: Input: S = "10011"Output: 1Explanation:Swap index 2 and index 3 and the string becomes 10101 . Input: S = "11010 11 min read
- Minimum swaps required to make a binary string alternating You are given a binary string of even length (2N) and an equal number of 0's (N) and 1's (N). What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal. Examples: Input : 000111Output : 1Explanation : Swap index 2 and 11 min read
- Minimum number of swaps required to sort an array | Set 2 Given an array of N distinct elements, find the minimum number of swaps required to sort the array. Note: The problem is not asking to sort the array by the minimum number of swaps. The problem is to find the minimum swaps in which the array can be sorted. Examples: Input: arr[] = {4, 3, 2, 1} Outpu 7 min read
- Minimum swaps to sort an array Given an array arr[] of distinct elements, find the minimum number of swaps required to sort the array.Examples: Input: arr[] = [2, 8, 5, 4]Output: 1Explanation: Swap 8 with 4 to get the sorted array.Input: arr[] = [10, 19, 6, 3, 5]Output: 2Explanation: Swap 10 with 3 and 19 with 5 to get the sorted 10 min read
- Minimum number of swaps required to sort an array of first N number Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array. Example: Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 } Output: 5 Explanation: i arr swap (indices) 0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3) 1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1) 2 [1, 5 min read
- Minimum swaps required to convert one binary string to another Given two binary string M and N of equal length, the task is to find a minimum number of operations (swaps) required to convert string N to M. Examples: Input: str1 = "1101", str2 = "1110" Output: 1 Swap last and second last element in the binary string, so that it become 1101 Input: str1 = "1110000 5 min read
- Minimum number of swaps required for arranging pairs adjacent to each other There are n-pairs and therefore 2n people. everyone has one unique number ranging from 1 to 2n. All these 2n persons are arranged in random fashion in an Array of size 2n. We are also given who is partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs b 15 min read
- Count swaps required to sort an array using Insertion Sort Given an array A[] of size N (1 ≤ N ≤ 105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm.Examples:Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation:Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Coun 15 min read
- Minimum Subarray reversals to sort given Binary Array Given a binary array A[] of size N, the task is to find the minimum number of subarrays that need to be reversed to sort the binary array. Examples: Input: N = 4, A[]: {1, 0 , 0, 1} Output: 1Explanation: Reverse the array from 0 to 2 to change the array to {0, 0, 1, 1} Input: N = 4, A[]: {1, 0, 1 , 5 min read
- Minimum subarray reversals required to make given binary array alternating Given a binary array arr[] consisting of equal count of 0s and 1s, the task is to count the minimum number of subarray reversal operations required to make the binary array alternating. In each operation reverse any subarray of the given array. Examples: Input: arr[] = { 1, 1, 1, 0, 1, 0, 0, 0 } Out 5 min read