Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum number of elements to be replaced to make the given array a Fibonacci Sequence
Next article icon

Minimum number of 1’s to be replaced in a binary array

Last Updated : 08 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary array arr[] of zero’s and one’s only. The task is to find the minimum number of one’s to be changed to zero such if there exist any index i      in the array such that arr[i] = 0 then arr[i-1] and arr[i+1] both should not be equals to 1      at the same time.

That is, for any index i      the below condition should fail: 

if (arr[i]== 0):     (arr[i-1] == 1) && (arr[i+1] == 1)

Note: 1-based indexing is considered for the array.

Examples: 

Input : arr[] = { 1, 1, 0, 1, 1, 0, 1, 0, 1, 0 } 
Output : 2 
Explanation: Indexes 2 and 7 OR 4 and 7 can be changed to zero.

Input : arr[] = { 1, 1, 0, 0, 0 } 
Output : 0  

Approach: The idea is that, whenever we found condition like arr[i-1] = 1 \;and\; arr[i] = 0 \;and \;arr[i+1] = 1      we simply changed the value of (i+1)th index to zero(0). So that index between (i-1)-th and (i+1)-th index is safe.

Below is the implementation of the above approach: 

C++

// C++ program to find minimum number
// of 1's  to be replaced to 0's
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number
// of 1's  to be replaced to 0's
int minChanges(int A[], int n)
{
    int cnt = 0;
 
    for (int i = 0; i < n - 2; ++i) {
 
        if ((i - 1 >= 0) && A[i - 1] == 1
            && A[i + 1] == 1 && A[i] == 0) {
            A[i + 1] = 0;
            cnt++;
        }
 
    }
 
    // return final answer
    return cnt;
}
 
// Driver program
int main()
{
    int A[] = { 1, 1, 0, 1, 1, 0, 1, 0, 1, 0 };
    int n = sizeof(A) / sizeof(A[0]);
 
    cout << minChanges(A, n);
 
    return 0;
}
                      
                       

Java

// Java program to find minimum number
// of 1's to be replaced to 0's
import java.lang.*;
import java.util.*;
 
class GFG
{
// Function to find minimum number
// of 1's to be replaced to 0's
static int minChanges(int[] A, int n)
{
    int cnt = 0;
 
    for (int i = 0; i < n - 2; ++i)
    {
 
        if ((i - 1 >= 0) && A[i - 1] == 1 &&
                            A[i + 1] == 1 &&
                            A[i] == 0)
        {
            A[i + 1] = 0;
            cnt++;
        }
 
    }
 
    // return final answer
    return cnt;
}
 
// Driver Code
public static void main(String args[])
{
    int[] A = { 1, 1, 0, 1, 1, 0, 1, 0, 1, 0 };
    int n = A.length;
 
    System.out.print(minChanges(A, n));
}
}
 
// This code is contributed
// by Akanksha Rai
                      
                       

Python3

# Python 3 program to find minimum
# number of 1's to be replaced to 0's
     
# Function to find minimum number
# of 1's to be replaced to 0's
def minChanges(A, n):
    cnt = 0
    for i in range(n - 2):
        if ((i - 1 >= 0) and A[i - 1] == 1 and
           A[i + 1] == 1 and A[i] == 0):
            A[i + 1] = 0
            cnt = cnt + 1
     
    # return final answer
    return cnt
     
# Driver Code
A = [1, 1, 0, 1, 1, 0, 1, 0, 1, 0]
n = len(A)
print(minChanges(A, n))
         
# This code is contributed
# by Shashank_Sharma
                      
                       

C#

// C# program to find minimum number
// of 1's to be replaced to 0's
using System;
 
class GFG
{
// Function to find minimum number
// of 1's to be replaced to 0's
static int minChanges(int[] A, int n)
{
    int cnt = 0;
 
    for (int i = 0; i < n - 2; ++i)
    {
 
        if ((i - 1 >= 0) && A[i - 1] == 1 &&
                            A[i + 1] == 1 && A[i] == 0)
        {
            A[i + 1] = 0;
            cnt++;
        }
 
    }
 
    // return final answer
    return cnt;
}
 
// Driver Code
public static void Main()
{
    int[] A = { 1, 1, 0, 1, 1, 0, 1, 0, 1, 0 };
    int n = A.Length;
 
    Console.Write(minChanges(A, n));
}
}
 
// This code is contributed
// by Akanksha Rai
                      
                       

PHP

<?php
// PHP program to find minimum number
// of 1's to be replaced to 0's
 
// Function to find minimum number
// of 1's to be replaced to 0's
function minChanges($A, $n)
{
    $cnt = 0;
 
    for ($i = 0; $i < $n - 2; ++$i)
    {
        if (($i - 1 >= 0) && $A[$i - 1] == 1 &&
          $A[$i + 1] == 1 && $A[$i] == 0)
        {
            $A[$i + 1] = 0;
            $cnt++;
        }
 
    }
 
    // return final answer
    return $cnt;
}
 
// Driver Code
$A = array(1, 1, 0, 1, 1,
           0, 1, 0, 1, 0);
$n = sizeof($A);
 
echo minChanges($A, $n);
 
// This code is contributed
// by Ankita_Saini
?>
                      
                       

Javascript

<script>
 
// Javascript program to find minimum number
// of 1's  to be replaced to 0's
 
// Function to find minimum number
// of 1's  to be replaced to 0's
function minChanges(A, n)
{
    var cnt = 0;
 
    for (var i = 0; i < n - 2; ++i) {
 
        if ((i - 1 >= 0) && A[i - 1] == 1
            && A[i + 1] == 1 && A[i] == 0) {
            A[i + 1] = 0;
            cnt++;
        }
 
    }
 
    // return final answer
    return cnt;
}
 
 
var A = [ 1, 1, 0, 1, 1, 0, 1, 0, 1, 0 ];
var n = A.length;
document.write(  minChanges(A, n));
 
 
// This code is contributed by SoumikMondal
 
</script>
                      
                       

Output
2

Complexity Analysis:

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


Next Article
Minimum number of elements to be replaced to make the given array a Fibonacci Sequence

S

Sanjit_Prasad
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Pattern Searching
  • binary-string
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Pattern Searching

Similar Reads

  • 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 chan
    6 min read
  • Minimum number of elements to be replaced to make the given array a Fibonacci Sequence
    Given an array arr containing N integer elements, the task is to count the minimum number of elements that need to be changed such that all the elements (after proper rearrangement) make first N terms of Fibonacci Series. Examples: Input: arr[] = {4, 1, 2, 1, 3, 7} Output: 2 4 and 7 must be changed
    6 min read
  • Minimum number of characters to be removed to make a binary string alternate
    Given a binary string, the task is to find minimum number of characters to be removed from it so that it becomes alternate. A binary string is alternate if there are no two consecutive 0s or 1s.Examples : Input : s = "000111" Output : 4 We need to delete two 0s and two 1s to make string alternate. I
    4 min read
  • Minimum number of steps required to place all 1s at a single index
    Given a binary array A[] of size N, where all 1s can be moved to its adjacent position, the task is to print an array res[] of size N, where res[i] contains the minimum number of steps required to move all the 1s at the ith index. Examples: Input: A[] = {1, 0, 1, 0}Output: {2, 2, 2, 4}Explanation: F
    9 min read
  • Minimum number of Binary strings to represent a Number
    Given a number N. The task is to find the minimum number of binary strings required to represent the given number as the sum of the binary strings.Examples: Input : 131 Output : Minimum Number of binary strings needed: 3 111 10 10 Input : 564 Output :Minimum Number of binary strings needed: 6 111 11
    7 min read
  • Minimum number of replacements to make the binary string alternating | Set 2
    Given a binary string str, the task is to find the minimum number of characters in the string that have to be replaced in order to make the string alternating (i.e. of the form 01010101... or 10101010...).Examples: Input: str = "1100" Output: 2 Replace 2nd character with '0' and 3rd character with '
    5 min read
  • Minimum length subarray of 1s in a Binary Array
    Given binary array. The task is to find the length of subarray with minimum number of 1s.Note: It is guaranteed that there is atleast one 1 present in the array.Examples : Input : arr[] = {1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} Output : 3 Minimum length subarray of 1s is {1, 1}.Input : arr[] = {0, 0, 1
    8 min read
  • Minimum time required to cover a Binary Array
    Given an integer N which represents the size of a boolean array that is initially filled with 0, and also given an array arr[] of size K consisting of (1-based) indices at which '1' are present in the boolean array. Now, at one unit of time the adjacent cells of the arr[i] in the boolean array becom
    8 min read
  • Minimum removals required to place all 0s before 1s in a Binary String
    Given a binary string S, the task is to find the minimum number of characters required to be removed from S, such that all the 0s are placed before 1s. Examples: Input: S = "001101"Output: 1Explanation: Removing S[4] (= '0') modifies the string S to "00111".Therefore, minimum number of deletions req
    6 min read
  • Maximum number of consecutive 1's in binary representation of all the array elements
    Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences