VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-1s-sorted-binary-array/

⇱ Count 1's in a sorted binary array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count 1's in a sorted binary array

Last Updated : 9 Feb, 2026

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
Explanation: Count of 1's in the given array is 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] Using linear Search - O(n) Time and O(1) Space

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.


Output
4

[Expected Approach] Using Binary Search - O(log n) Time and O(1) Space

Since the array is sorted with all 1s before 0s, there is a single transition point from 1 to 0. We use binary search to find the last occurrence of 1 by checking the middle element and narrowing the search space accordingly. The index of this last 1 plus one gives the count.


Output
4
Comment
Article Tags: