Given a binary array arr[] of size N, which is 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
Naive approach:
A simple solution is to linearly traverse the array until we find the 1’s in the array and keep count of 1s. If the array element becomes 0 then return the count of 1’s.
Time Complexity: O(N).
Auxiliary Space: O(1)
Count 1’s in a sorted binary array using Binary search recursively:
We can use Binary Search to find count in O(Logn) time. The idea is to look for the last occurrence of 1 using Binary Search. Once we find the index’s last occurrence, we return index + 1 as count.
Follow the steps below to implement the above idea:
- Do while low <= high:
- Calculate mid using low + (high – low) / 2.
- Check if the element at mid index is the last 1
- If the element is not last 1, move the low to right side recursively and return the result received from it.
- Otherwise, move the low to left recursively and return the result received from it.
The following is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
int countOnes( bool 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;
}
int main()
{
bool arr[] = { 1, 1, 1, 1, 0, 0, 0 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Count of 1's in given array is "
<< countOnes(arr, 0, n - 1);
return 0;
}
|
Python3
def countOnes(arr, low, high):
if high > = low:
mid = low + (high - low) / / 2
if ((mid = = high or arr[mid + 1 ] = = 0 ) and (arr[mid] = = 1 )):
return mid + 1
if arr[mid] = = 1 :
return countOnes(arr, (mid + 1 ), high)
return countOnes(arr, low, mid - 1 )
return 0
arr = [ 1 , 1 , 1 , 1 , 0 , 0 , 0 ]
print ( "Count of 1's in given array is" , countOnes(arr, 0 , len (arr) - 1 ))
|
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 ));
}
}
|
C#
using System;
class GFG {
static 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()
{
int [] arr = { 1, 1, 1, 1, 0, 0, 0 };
int n = arr.Length;
Console.WriteLine( "Count of 1's in given "
+ "array is "
+ countOnes(arr, 0, n - 1));
}
}
|
PHP
<?php
function countOnes( $arr , $low , $high )
{
if ( $high >= $low )
{
$mid = $low + ( $high - $low )/2;
if ( ( $mid == $high or $arr [ $mid +1] == 0)
and ( $arr [ $mid ] == 1))
return $mid +1;
if ( $arr [ $mid ] == 1)
return countOnes( $arr , ( $mid + 1),
$high );
return countOnes( $arr , $low , ( $mid -1));
}
return 0;
}
$arr = array (1, 1, 1, 1, 0, 0, 0);
$n = count ( $arr );
echo "Count of 1's in given array is " ,
countOnes( $arr , 0, $n -1);
?>
|
Javascript
<script>
function countOnes( arr, low, high)
{
if (high >= low)
{
let mid = Math.trunc(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;
}
let arr = [ 1, 1, 1, 1, 0, 0, 0 ];
let n = arr.length;
document.write( "Count of 1's in given array is " +
countOnes(arr, 0, n-1));
</script>
|
Output
Count of 1's in given array is 4
Time complexity: O(Log(N))
Auxiliary Space: O(log(N))
Count 1’s in a sorted binary array using binary search iteratively:
Follow the steps below for the implementation:
- Do while low <= high
- Calculate the middle index say mid
- Check if arr[mid] is less than 1 then move the high to left side (i.e, high = mid – 1)
- If the element is not last 1 then move the low to the right side (i.e, low = mid + 1)
- Check if the element at the middle index is last 1 then return mid + 1
- Otherwise move to low to right (i.e, low = mid + 1)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countOnes( bool 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;
}
}
}
int main()
{
bool arr[] = { 1, 1, 1, 1, 0, 0, 0 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Count of 1's in given array is "
<< countOnes(arr, n);
return 0;
}
|
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));
}
}
|
Python3
def countOnes(arr, n):
low = 0
high = n - 1
while (low < = high):
mid = (low + high) / / 2
if (arr[mid] < 1 ):
high = mid - 1
elif (arr[mid] > 1 ):
low = mid + 1
else :
if (mid = = n - 1 or arr[mid + 1 ] ! = 1 ):
return mid + 1
else :
low = mid + 1
return 0
if __name__ = = '__main__' :
arr = [ 1 , 1 , 1 , 1 , 0 , 0 , 0 ]
n = len (arr)
print ( "Count of 1's in given array is " , countOnes(arr, n))
|
C#
using System;
public class GFG {
static int countOnes( int [] arr, int n)
{
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;
Console.WriteLine( "Count of 1's in given array is "
+ countOnes(arr, n));
}
}
|
Javascript
<script>
function countOnes(arr,n)
{
let ans;
let low = 0, high = n - 1;
while (low <= high) {
let mid = Math.floor((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;
}
}
}
let arr=[ 1, 1, 1, 1, 0, 0, 0];
let n = arr.length;
document.write( "Count of 1's in given array is " + countOnes(arr, n));
</script>
|
Output
Count of 1's in given array is 4
Time complexity: O(Log(N))
Auxiliary Space: O(log(N))
Count 1’s in a sorted binary array using inbuilt functions:
Below is the implementation using inbuilt functions:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 1, 1, 1, 1, 0, 0, 0, 0, 0 };
int size = sizeof (arr) / sizeof (arr[0]);
auto ptr
= upper_bound(arr, arr + size, 1, greater< int >());
cout << "Count of 1's in given array is "
<< (ptr - arr);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
int [] arr = { 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 };
int size = arr.length;
long total = Arrays.stream(arr)
.filter(i -> i == 1 )
.count();
System.out.println( "Count of 1's in given array is "
+ total);
}
}
|
Python3
arr = [ 1 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 ]
print ( "Count of 1's in given array is " ,arr.count( 1 ))
|
Javascript
const arr = [1, 1, 1, 1, 0, 0, 0, 0, 0];
const size = arr.length;
const ptr = arr.findIndex((el) => el === 0);
console.log(`Count of 1 's in given array is ${ptr}`);
|
C#
using System;
using System.Linq;
class GFG{
static public void Main()
{
var total = 0;
int [] colors = { 1, 1, 1, 1, 0, 0, 0, 0, 0 };
total = colors.Count(c => c == 1);
Console.WriteLine( "Count of 1's in given array is " +total);
}
}
|
Output
Count of 1's in given array is 4
Time Complexity: O(Log(N))
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
23 Mar, 2023
Like Article
Save Article