Competitive ProgrammingEasy

Count 1s in Binary Array

Detailed guide and Python implementation for the 'Count 1s in Binary Array' problem.

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?
Consider using Searching & Sorting-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.