Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.
Since the input array is sorted, we can use Binary Search to find the first occurrence of 0. Once we have index of first element, we can return count as n – index of first zero.
Read full article from Find the number of zeroes | GeeksforGeeks
Since the input array is sorted, we can use Binary Search to find the first occurrence of 0. Once we have index of first element, we can return count as n – index of first zero.
int
firstZero(
int
arr[],
int
low,
int
high)
{
if
(high >= low)
{
// Check if mid element is first 0
int
mid = low + (high - low)/2;
if
(( mid == 0 || arr[mid-1] == 1) && arr[mid] == 0)
return
mid;
if
(arr[mid] == 1)
// If mid element is not 0
return
firstZero(arr, (mid + 1), high);
else
// If mid element is 0, but not first 0
return
firstZero(arr, low, (mid -1));
}
return
-1;
}