Back to Practice Dashboard
Competitive ProgrammingEasy
Count 1s in Binary Array
Learn how to solve the 'Count 1s in Binary Array' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
Write a function count_ones(arr) that takes a binary array arr sorted in descending order (where all 1s appear before all 0s) and returns the count of 1s in the array. Your solution should run in O(log n) time.
Constraints
- •0 <= len(arr) <= 10^5
- •arr[i] is either 0 or 1
Examples
Example 1
Input
count_ones([1, 1, 1, 1, 0, 0, 0])
Output
4
Explanation
There are four 1s at the beginning of the array.
Example 2
Input
count_ones([1, 1, 0, 0, 0])
Output
2
Explanation
There are two 1s at the beginning of the array.
Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.