VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-swaps-required-group-1s-together/

⇱ Minimum Swaps to group all 1s - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Swaps to group all 1s

Last Updated : 23 Apr, 2026

Given an array of 0's and 1's, we need to find the minimum swaps required to group all 1's present in the array together. In a swap operation, we swap two elements at different indexes.

Examples:

Input: arr[] = [1, 0, 1, 0, 1]
Output: 1
Explanation: Only 1 swap is required to group all 1's together. Swapping index 1 with 4 will give arr[] = [1, 1, 1, 0, 0]

Input: arr[] = [1, 1, 0, 1, 0, 1, 1]
Output: 2
Explanation: Only 2 swap is required to group all 1's together. Swapping index 0 with 2 and 1 with 4 will give arr[] = [0, 0, 1, 1, 1, 1, 1]

Input: arr[] = [0, 0, 0]
Output: -1
Explanation: No 1s are present in the array, so return -1.

[Naive Approach] Using Nested loops - O(n^2) Time and O(n) Space

The idea is based on the fact that a subarray with more 1s would require less swaps.

  • Count total number of 1’s in the array. To group 1s, we need to know how many 1s are there. Let this count be x.
  • Find the subarray of length x with maximum number of 1’s. To group all 1s, we need to choose a subarray that has more 1s as would require less swaps.
  • The minimum swaps required will be the number of 0’s in this subarray of length x.

Output
1

[Expected Approach] Maintaining Window K(count of 1) - O(n) Time and O(1) Space

This is mainly an optimization over the above approach. Count the total number of 1s (x) in the array, then find a subarray of length x with the maximum 1s using a sliding count. Track the maximum 1s in any such subarray and return x - maxOnes as the minimum swaps needed.

  • Given arr = {1, 0, 1, 0, 1}, total number of 1s x = 3, so required window size = 3
  • Consider all subarrays of size 3 and count number of 1s in each
  • [1, 0, 1] have 2 ones, [0, 1, 0] have 1 one, [1, 0, 1] have 2 ones
  • Maximum 1s in any window = maxOnes = 2
  • Minimum swaps required = number of 0s in best window = x - maxOnes = 3 - 2 = 1

Output
1
Comment
Article Tags: