Fill array with 1's using minimum iterations of filling neighbors in C++


 In this problem, we are given an array arr consisting of n elements that are either 0 or 1. Our task is to fill array with 1’s using minimum iterations of filling neighbors. 

Let’s take an example to understand the problem,

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

Output: 1

Solution Approach −

To solve the problem, we need to know the fact that if 1 is present in a position it can convert two neighbouring 0’s to 1.

If,                arr[i] is 1.
Then,           arr[i-1] and arr[i+1] will be converted to 1.

Using this, the solution can be found using one of these case −

Case 1: Block has 1’s at start and end of the block. Rest all values are 0. Count the number of zeros.

Number of iterations = zeroCount / 2 if count is even

Number of iteration = (zeroCount -1)/2 if count is odd

Case 2: Block has single 1 at start or end of the block and rest all values are 0.

Number of iterations = zeroCount

Case 3: Block has no 1’s. Print -1 denoting filling of 1’s not possible.

Program to illustrate the working of our solution,

Example

Live Demo

#include<iostream>
using namespace std;

int countIterationFill1(int arr[], int n) {
   
   bool oneFound = false;
   int iterationCount = 0;
   for (int i=0; i<n; ) {
      
      if (arr[i] == 1)
      oneFound = true;
      while (i<n && arr[i]==1)
         i++;
      int zeroCount = 0;
      while (i<n && arr[i]==0) {
         zeroCount++;
         i++;
      }
      if (oneFound == false && i == n)
         return -1;
      int itrCount;
      if (i < n && oneFound == true) {
         
         if (zeroCount & 1 == 0)
            itrCount = zeroCount/2;
         else
            itrCount = (zeroCount+1)/2;
         zeroCount = 0;
      }
      else{
         
         itrCount = zeroCount;
         zeroCount = 0;
      }
      iterationCount = max(iterationCount, itrCount);
   }

   return iterationCount;
}

int main() {
   
   int arr[] = {0, 1, 1, 0, 0, 1, 0, 0, 0, 1};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The number of iterations to fill 1's is "<<countIterationFill1(arr, n);
   return 0;
}

Output −

The number of iterations to fill 1's is 2

Updated on: 22-Jan-2021

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements