Minimum flips to remove every 101 pattern in a binary array

Updated

Given a binary array, find the minimum number of flips such that the below condition is false for every index i.

  • a[i]=0, a[i+1] = 1 and a[i-1] = 1

Examples :

Input : a[] = {1, 1, 0, 1, 1, 0, 1, 0, 1, 0}
Output : 2
Flipping bits at index 3 and 6 will be the minimal possible.

Input : a[] = {1, 1, 0, 0, 0}
Output : 0
No flip of bits are required.

Approach :

We could follow a greedy approach to solve this problem. Traverse from the left side of the array, check for the given condition, if it is true, then flip the bit of the i+1-th index and count the flip.

Implementation :

// C++ program to find the minimal 
// number of flips required 
#include<bits/stdc++.h> 
using namespace std;

// Function to count the minimal flips 
int minimalFlips(int a[], int n)
{
    int count = 0;
// traverse greedily 
    for(int i = 1;i<n-1;i++)
    {
        // check for the given condition 
        if(!a[i])
        {

            if(a[i-1] && a[i+1])
            {

                // increase the count 
                count += 1;
                a[i+1] = 0;
            }
        }
    }
    return count;  
} 

// Driver Code
int main()
{
    int a[] = {1, 1, 0, 1, 1, 0, 1, 0, 1, 0}; 
    int n = sizeof(a)/sizeof(a[0]); 
    cout << minimalFlips(a,n); 
} 
Comment
Mithlesh Upadhyay Published 26 Nov 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials