Minimum number of moves to make a binary array K periodic

Given a binary array arr[] (containing only 0s and 1s) and an integer K. The task is to find the minimum number of moves to make the array K-periodic.
An array is said to be K-periodic if the sub-arrays [1 to K], [k+1 to 2K], [2k+1 to 3K], … are all exactly same.
In a single move any 1 can be changed to a 0 or any 0 can be changed into a 1.

Examples:

Input: arr[] = {1, 1, 0, 0, 1, 1}, K = 2
Output: 2
The new array can be {1, 1, 1, 1, 1, 1}

Input: arr[] = {1, 0, 0, 0, 1, 0}, K = 2
Output: 1
The new array can be {1, 0, 1, 0, 1, 0}



Approach: For an array to be K-periodic. Consider indices i where i % K = X. All these indices must have the same value. So either the 1s can be converted to 0s or vice-versa. In order to reduce the number of moves, we choose the conversion which is minimum.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the minimum moves required
int minMoves(int n, int a[], int k)
{
  
    int ct1[k] = { 0 }, ct0[k] = { 0 }, moves = 0;
  
    // Count the number of 1s and 2s
    // at each X such that i % K = X
    for (int i = 0; i < n; i++)
        if (a[i] == 1)
            ct1[i % k]++;
        else
            ct0[i % k]++;
  
    // Choose the minimum elements to change
    for (int i = 0; i < k; i++)
        moves += min(ct1[i], ct0[i]);
  
    // Return the minimum moves required
    return moves;
}
  
// Driver code
int main()
{
    int k = 2;
    int a[] = { 1, 0, 0, 0, 1, 0 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << minMoves(n, a, k);
  
    return 0;
}

chevron_right


Output:

1

Time Complexity: O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.