VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-swaps-to-group-all-0s-together-in-binary-circular-array/

⇱ Minimum swaps to group all 0s together in Binary Circular Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum swaps to group all 0s together in Binary Circular Array

Last Updated : 23 Jul, 2025

Given a binary circular array arr[] of size N, the task is to find the minimum swaps to group all 0s together in the array.

Examples:

Input: arr[] = {1, 0, 1, 0, 0, 1, 1}
Output: 1
Explanation: Here are a few of the ways to group all the 0's together:

  1. {1, 0, 0, 1, 1} using 1 swap.
  2. {1, 0, 0, 1, 1} using 1 swap.
  3. {0, 0, 1, 1, 1, 1, 0} using 2 swaps (using the circular property of the array).

There is no way to group all 0's together with 0 swaps. Thus, the minimum number of swaps required is 1.


Input: arr[] = {0, 0, 1, 1, 0}
Output: 0
Explanation: All the 0's are already grouped together due to the circular property of the array. 
Thus, the minimum number of swaps required is 0.

Approach: The task can be solved using the sliding window technique. Follow the below steps to solve the problem:

  • Count the total number of 0s. Let m be that number
  • Find the contiguous region of length m that has the most 0s in it
  • The number of 1s in this region is the minimum required swaps. Each swap will move one 0 into the region and one 1 out of the region.
  • Finally, use modulo operation for handling the case of the circular arrays.

Below is the implementation of the above approach.

 
 


Output
1


 

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment