Prepin
Log in

Determine the count of 1's in a sorted binary array.

Approach / Explanation

This question involves a sorted binary array, which consists solely of 0s and 1s. A 'sorted' binary array means that all 0s are positioned before any 1s. An example of such an array is: [0,0,0,1,1,1]. Your objective is to determine how many 1s are present in this binary array. Since the array is sorted, you can leverage this characteristic to devise an efficient solution. A simple approach might be to iterate through each element and count the 1s; however, utilizing the sorted nature of the array allows us to apply binary search, thereby improving time efficiency. Important points to keep in mind: The binary array is in sorted order. You can use binary search to identify the point where 0s end and 1s begin. After locating this transition point, the count of 1s can be determined by subtracting the transition index from the total length of the array.

Suggested Answer

For example, take the binary array: [0,0,0,1,1,1]. This array is sorted, meaning all the 0s are positioned before the 1s. The initial step involves identifying the transition point using binary search. In this instance, the transition point occurs where the last 0 ends and the first 1 begins, which is at index 3. Given that the array has a length of 6, we calculate the number of 1s by subtracting the transition index from the size of the array: 6 - 3 = 3. Therefore, there are 3 ones in this sorted binary array. Below is a Python code snippet that accomplishes this: def countOnes ( arr ) : # binary search to find transition point low = 0 high = len ( arr ) - 1 while low <= high : mid = ( low + high ) // 2 if arr [ mid ] == 0 : low = mid + 1 else : if mid == 0 or arr [ mid - 1 ] == 0 : return len ( arr ) - mid else : high = mid - 1 print ( countOnes ( [ 0 , 0 , 0 , 1 , 1 , 1 ] ) ) # output: 3

Alternative Answer

Let's look at another example using the array: [0, 0, 1, 1, 1, 1, 1]. By conducting a binary search, we identify the transition point at index 2. The array's total length is 7. When we subtract the transition index from the length of the array, we calculate 7 - 2 = 5. Thus, this sorted binary array contains 5 ones. The same Python function previously defined can be applied to this scenario: print ( countOnes ( [ 0 , 0 , 1 , 1 , 1 , 1 , 1 ] ) ) # output: 5

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.