Open In App

Minimum subarray reversals required to make given binary array alternating

Last Updated : 21 Apr, 2021
Summarize
Comments
Improve
Suggest changes
Share
4 Likes
Like
Report

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 } 
Output:
Explanation: 
Reversing the subarray {arr[1], ..., arr[5]} modifies arr[] to { 1, 0, 1, 0, 1, 1, 0, 0 } 
Reversing the subarray {arr[5], arr[6]} modifies arr[] to { 1, 0, 1, 0, 1, 0, 1, 0 }, which is alternating. Therefore, the required output is 2.

Input: arr[] = { 0, 1, 1, 0 } 
Output:
Explanation: 
Reversing the subarray {arr[2], ..., arr[2]} modifies arr[] to { 0, 1, 0, 1 }, which is alternating. Therefore, the required output is 1.

Approach: The problem can be solved using Greedy technique. The idea is to count the array elements which are not present at correct indices for the array to be alternating, i.e. count the consecutive equal elements present the given array. Follow the steps below to solve the problem:

  • Initialize a variable, say cntOp, to store the minimum count of subarray reversal operations required to make the given array alternating.
  • Traverse the array using variable i and for every array element arr[i], check if it is equal to arr[i + 1] or not. If found to be true, then increment the value of cntOp.
  • Finally, print the value of (cntOp + 1) / 2. 
     

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output: 
2

 

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


 


Next Article

Similar Reads