Java Program to Count 1’s in a sorted binary array
Given a binary array sorted in non-increasing order, count the number of 1’s in it.Â
Examples:Â
Input: arr[] = {1, 1, 0, 0, 0, 0, 0}
Output: 2
Input: arr[] = {1, 1, 1, 1, 1, 1, 1}
Output: 7
Input: arr[] = {0, 0, 0, 0, 0, 0, 0}
Output: 0
A simple solution is to linearly traverse the array. The time complexity of the simple solution is O(n). We can use Binary Search to find count in O(Logn) time. The idea is to look for last occurrence of 1 using Binary Search. Once we find the index last occurrence, we return index + 1 as count.
The following is the implementation of above idea.Â
Java
class CountOnes
{
int countOnes( int arr[], int low, int high)
{
if (high >= low)
{
int mid = low + (high - low) / 2 ;
if ((mid == high || arr[mid + 1 ] == 0 )
&& (arr[mid] == 1 ))
return mid + 1 ;
if (arr[mid] == 1 )
return countOnes(arr, (mid + 1 ), high);
return countOnes(arr, low, (mid - 1 ));
}
return 0 ;
}
public static void main(String args[])
{
CountOnes ob = new CountOnes();
int arr[] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 };
int n = arr.length;
System.out.println( "Count of 1's in given array is "
+ ob.countOnes(arr, 0 , n - 1 ));
}
}
|
Output
Count of 1's in given array is 4
Time complexity of the above solution is O(Logn)
Space complexity o(log n) (function call stack)
The same approach with iterative solution would be
Java
import java.io.*;
class GFG
{
static int countOnes( int arr[], int n)
{
int ans;
int low = 0 , high = n - 1 ;
while (low <= high) {
int mid = (low + high) / 2 ;
if (arr[mid] < 1 )
high = mid - 1 ;
else if (arr[mid] > 1 )
low = mid + 1 ;
else
{
if (mid == n - 1 || arr[mid + 1 ] != 1 )
return mid + 1 ;
else
low = mid + 1 ;
}
}
return 0 ;
}
public static void main (String[] args) {
int arr[] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 };
int n = arr.length;
System.out.println( "Count of 1's in given array is " + countOnes(arr, n));
}
}
|
Output
Count of 1's in given array is 4
Time complexity of the above solution is O(Logn)
Space complexity is O(1)
Please refer complete article on Count 1’s in a sorted binary array for more details!
Last Updated :
27 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...