Count 1's in a sorted binary array - GeeksforGeeks

28 Feb, 2022
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. 
C++
Python3
Java
C#
PHP
Javascript
// C++ program to count one's in a boolean array#include <bits/stdc++.h>using namespace std; /* Returns counts of 1's in arr[low..high].  The array is   assumed to be sorted in non-increasing order */int countOnes(bool arr[], int low, int high){  if (high >= low)  {    // get the middle index    int mid = low + (high - low)/2;     // check if the element at middle index is last 1    if ( (mid == high || arr[mid+1] == 0) && (arr[mid] == 1))      return mid+1;     // If element is not last 1, recur for right side    if (arr[mid] == 1)      return countOnes(arr, (mid + 1), high);     // else recur for left side    return countOnes(arr, low, (mid -1));  }  return 0;} /* Driver Code */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;}
# Python program to count one's in a boolean array # Returns counts of 1's in arr[low..high].  The array is# assumed to be sorted in non-increasing orderdef countOnes(arr,low,high):         if high>=low:                 # get the middle index        mid = low + (high-low)//2                 # check if the element at middle index is last 1        if ((mid == high or arr[mid+1]==0) and (arr[mid]==1)):            return mid+1                     # If element is not last 1, recur for right side        if arr[mid]==1:            return countOnes(arr, (mid+1), high)                     # else recur for left side        return countOnes(arr, low, mid-1)         return 0 # Driver Codearr=[1, 1, 1, 1, 0, 0, 0]print ("Count of 1's in given array is",countOnes(arr, 0 , len(arr)-1)) # This code is contributed by __Devesh Agrawal__
// Java program to count 1's in a sorted arrayclass CountOnes{    /* Returns counts of 1's in arr[low..high].  The       array is assumed to be sorted in non-increasing       order */    int countOnes(int arr[], int low, int high)    {        if (high >= low)        {            // get the middle index            int mid = low + (high - low) / 2;             // check if the element at middle index is last            // 1            if ((mid == high || arr[mid + 1] == 0)                && (arr[mid] == 1))                return mid + 1;             // If element is not last 1, recur for right            // side            if (arr[mid] == 1)                return countOnes(arr, (mid + 1), high);             // else recur for left side            return countOnes(arr, low, (mid - 1));        }        return 0;    }     /* Driver code */    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));    }}/* This code is contributed by Rajat Mishra */
// C# program to count 1's in a sorted arrayusing System; class GFG {     /* Returns counts of 1's in arr[low..high].    The array is assumed to be sorted in    non-increasing order */    static int countOnes(int[] arr, int low, int high)    {        if (high >= low)        {            // get the middle index            int mid = low + (high - low) / 2;             // check if the element at middle            // index is last 1            if ((mid == high || arr[mid + 1] == 0)                && (arr[mid] == 1))                return mid + 1;             // If element is not last 1, recur            // for right side            if (arr[mid] == 1)                return countOnes(arr, (mid + 1), high);             // else recur for left side            return countOnes(arr, low, (mid - 1));        }         return 0;    }     /* Driver code */    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));    }} // This code is contributed by Sam007
<?php// PHP program to count one's in a// boolean array /* Returns counts of 1's in arr[low..high].The array is assumed to be sorted innon-increasing order */function countOnes( $arr, $low, $high){    if ($high >= $low)    {        // get the middle index        $mid = $low + ($high - $low)/2;             // check if the element at middle        // index is last 1        if ( ($mid == $high or $arr[$mid+1] == 0)                           and ($arr[$mid] == 1))            return $mid+1;             // If element is not last 1, recur for        // right side        if ($arr[$mid] == 1)            return countOnes($arr, ($mid + 1),                                          $high);             // else recur for left side        return countOnes($arr, $low, ($mid -1));    }         return 0;} /* Driver code */$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); // This code is contributed by anuj_67.?>
<script> // Javascript program to count one's in a boolean array /* Returns counts of 1's in arr[low..high].  The array is   assumed to be sorted in non-increasing order */function countOnes( arr, low, high){  if (high >= low)  {    // get the middle index    let mid = Math.trunc(low + (high - low)/2);     // check if the element at middle index is last 1    if ( (mid == high || arr[mid+1] == 0) && (arr[mid] == 1))      return mid+1;     // If element is not last 1, recur for right side    if (arr[mid] == 1)      return countOnes(arr, (mid + 1), high);     // else recur for left side    return countOnes(arr, low, (mid -1));  }  return 0;}    // Driver program        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>
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
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;/* Returns counts of 1's in arr[low..high].  The array is   assumed to be sorted in non-increasing order */ int countOnes(bool arr[], int n){    int ans;    int low = 0, high = n - 1;    while (low <= high) { // get the middle index        int mid = (low + high) / 2;         // else recur for left side        if (arr[mid] < 1)            high = mid - 1;        // If element is not last 1, recur for right side        else if (arr[mid] > 1)            low = mid + 1;        else        // check if the element at middle index is last 1        {            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;}
/*package whatever //do not write package name here */import java.io.*; class GFG{     static int countOnes(int arr[], int n){    int ans;    int low = 0, high = n - 1;    while (low <= high) { // get the middle index        int mid = (low + high) / 2;          // else recur for left side        if (arr[mid] < 1)            high = mid - 1;               // If element is not last 1, recur for right side        else if (arr[mid] > 1)            low = mid + 1;        else                   // check if the element at middle index is last 1        {            if (mid == n - 1 || arr[mid + 1] != 1)                return mid + 1;            else                low = mid + 1;        }    }    return 0;}       // Driver code    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));    }} // This code is contributed by patel2127.
'''package whatever #do not write package name here '''def countOnes(arr, n):    low = 0;    high = n - 1;    while (low <= high): # get the middle index        mid = (low + high) // 2;         # else recur for left side        if (arr[mid] < 1):            high = mid - 1;         # If element is not last 1, recur for right side        elif(arr[mid] > 1):            low = mid + 1;        else:         # check if the element at middle index is last 1            if (mid == n - 1 or arr[mid + 1] != 1):                return mid + 1;            else:                low = mid + 1;             return 0; # Driver codeif __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)); # This code is contributed by umadevi9616
/*package whatever //do not write package name here */using System;public class GFG {   static int countOnes(int []arr, int n) {     int low = 0, high = n - 1;    while (low <= high) { // get the middle index      int mid = (low + high) / 2;       // else recur for left side      if (arr[mid] < 1)        high = mid - 1;       // If element is not last 1, recur for right side      else if (arr[mid] > 1)        low = mid + 1;      else         // check if the element at middle index is last 1      {        if (mid == n - 1 || arr[mid + 1] != 1)          return mid + 1;        else          low = mid + 1;      }    }    return 0;  }   // Driver code  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));  }} // This code is contributed by umadevi9616
<script>/* Returns counts of 1's in arr[low..high].  The array is   assumed to be sorted in non-increasing order */ function countOnes(arr,n){    let ans;    let low = 0, high = n - 1;    while (low <= high) { // get the middle index        let mid = Math.floor((low + high) / 2);          // else recur for left side        if (arr[mid] < 1)            high = mid - 1;        // If element is not last 1, recur for right side        else if (arr[mid] > 1)            low = mid + 1;        else        // check if the element at middle index is last 1        {            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));  // This code is contributed by unknown2108</script>
Count of 1's in given array is 4
Time complexity of the above solution is O(Logn)
Space complexity is O(1)
The function will return the pointer to the index after the last occurrence of the element which we pass into the function.
We can use it here as the array is sorted in non-increasing order. 
int arr[] = {1,1,1,1,0,0,0,0};
int size = sizeof(arr)/sizeof(arr[0]);
auto ptr = upper_bound( arr, arr + size, 1, greater<int>() );
upper_bound() will return the iterator to the index after the last occurrence of 1. 
Here, ptr will point to index 4 of the array, i.e, after the last 1.
We need to use the greater<int>() function since the array is reverse sorted, i.e, 1s occur before 0s.
Now, subtracting the pointer to the array beginning from ptr ( ptr – arr ) will give us the number of 1s.
since the (pointer to first 0 – pointer to array beginning) = number of 1s
just like index of first 0 (4) – index of array beginning (0) = number of 1s 
int no_of_1 = ptr - arr;
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]);           // Pointer to the first occurence of zero       auto ptr        = upper_bound(arr, arr + size, 1, greater<int>());    cout << "Count of 1's in given array is " << (ptr - arr);     return 0;}
Count of 1's in given array is 4
The time complexity of the above solution is O(Logn).
Space complexity is O(1).
YouTubeGeeksforGeeks502K subscribersCount 1’s in a sorted binary array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=EoO9c9UOyww" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
vt_m
jeetpareshshah
jana_sayantan
anushikasethh
unknown2108
patel2127
umadevi9616
amartyaghoshgfg
sudip5banerjee1974
Binary Search
binary-string
Searching
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
3 Different ways to print Fibonacci series in Java
Program to remove vowels from a String
Find whether an array is subset of another array | Added Method 5
Find common elements in three sorted arrays
Non-Repeating Element
Recursive Programs to find Minimum and Maximum elements of array
Find closest number in array
Search, insert and delete in a sorted array
Check if a string contains uppercase, lowercase, special characters and numeric values