Competitive Programming簡単

Count 1s in Binary Array

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

問題提起

簡単

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.

制約
  • 0 <= len(arr) <= 10^5
  • arr[i] is either 0 or 1

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

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。