Ctrl K

Ones in Every Number

Easy
You get an integer limit. For each number from 0 to limit inclusive, count the ones in its binary form. Return a list of length limit + 1 whose element at position i is the number of ones in i. Counting the bits of each number from scratch takes O(n log n). Try for O(n) without a built-in bit count.
Example 1
limit=4 → [0, 1, 1, 2, 1]

0 → 0, 1 → 1, 2 → 10, 3 → 11, 4 → 100. Their ones: 0, 1, 1, 2, 1.

Example 2
limit=7 → [0, 1, 1, 2, 1, 2, 2, 3]

Adding 5 → 101, 6 → 110 and 7 → 111 gives 2, 2 and 3.

Example 3
limit=0 → [0]
Constraints
  • 0 ≤ limit ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNine-Dot Lock Patterns MediumSteps Down to One MediumShared Pool Race to a Goal MediumSettle Up in the Fewest Transfers HardSquare Frame From Sticks Medium
loading Python…
Input
limit=4
Expected
[0, 1, 1, 2, 1]

Run checks the first 3 tests in your browser. Submit checks all 36 tests on the server, hidden ones included.