Monday, October 6, 2025
HomeData Modelling & AIPython Program to Count 1’s in a sorted binary array

Python 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. 

Python




# 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 order
def 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=[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__


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)

Please refer complete article on Count 1’s in a sorted binary array for more details!

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 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32338 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6825 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6779 POSTS0 COMMENTS