Find the number of zeroes using C++

C++Server Side ProgrammingProgramming

In this problem, we are given a binary array bin[] consisting of only 0’s and 1’s. Our task is to find the number of zeroes.

The array is sorted i.e. all 0’s are arranged together after 1’s.

Let’s take an example to understand the problem,

Input

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

Output

4

Solution Approach

A simple solution to the problem is using the fact that the array is sorted, that is the number of 0’s in the array can be found using the first occurrence of 0 in the array. As after the first occurrence all values will be zero.

For finding the first occurrence of 0 in the array. We can use searching algorithms.

Linear Search − In linear search for the first 0, we will traverse the whole array till the first 0 is not encountered then we will return the count using first occurrence and size of the array. Using this solution we make the time complexity of the problem O(N).

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findFirstZero(int arr[], int n){
   for(int i = 0; i < n; i++){
      if(arr[i] == 0){
         return i;
      }
   }
   return -1;
}
int countZerosArr(int arr[], int n){
   int firstOccZero = findFirstZero(arr, n);
   if (firstOccZero == -1)
      return 0;
      return (n - firstOccZero);
   }
int main(){
   int arr[] = {1, 1, 1, 1, 0, 0, 0, 0, 0};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The count of zeros in array is "<<countZerosArr(arr, n);
   return 0;
}

Output

The count of zeros in array is 5

Binary Search − in binary search, we will find the first 0 by dividing the array's section based on whether the element at mid is 1 or 0. And return the index of the first occurrence of 0.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findFirstZero(int arr[], int start, int end){
   if (end >= start){
      int mid = start + (end - start) / 2;
      if ((mid == 0 || arr[mid - 1] == 1) && arr[mid] == 0)
         return mid;
      if (arr[mid] == 1)
         return findFirstZero(arr, (mid + 1), end);
      else
         return findFirstZero(arr, start, (mid -1));
   }
   return -1;
}
int countZerosArr(int arr[], int n){
   int firstOccZero = findFirstZero(arr, 0, n - 1);
   if (firstOccZero == -1)
      return 0;
      return (n - firstOccZero);
}
int main(){
   int arr[] = {1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The count of zeros in array is "<<countZerosArr(arr, n);
   return 0;
}

Output

The count of zeros in array is 7
raja
Updated on 11-Feb-2022 11:22:03

Advertisements