You are given a whole number n. For every number i from 0 up to n, count how many of its binary digits are 1. For example 6 is 110 in binary, so its count is 2.
Return the counts as a list ans of length n + 1, where ans[i] is the count for i. Try to do it without a built-in bit-count function, in one pass over the numbers.
Example 1
Input: n = 3 Output: [0, 1, 1, 2] Why: 0, 1, 10 and 11 in binary
2 more examples and the constraints
Example 2
Input: n = 6 Output: [0, 1, 1, 2, 1, 2, 2] Why: 4 is 100, 5 is 101, 6 is 110
Example 3
Input: n = 0 Output: [0] Why: only 0, which has no 1 bits
Constraints
- 0 ≤ n ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count each number's bitsO(n log n)
- Reuse i >> 1O(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 100,000 | Verdict |
|---|---|---|---|
| Count each number's bits | O(n log n) | Passes; misses the follow-up | |
| Reuse i >> 1 | O(n) | Best; one line per number |
n = the largest number; log n is about 17 at the limit.
Edge cases to test
- n = 0. The answer is [0], a list with one item, not an empty list.
- Powers of two. 8 is 1000: one bit. The count drops back to 1 at every power of two.
- All ones. 15 is 1111: four bits, the most for numbers below 16.
Common mistakes
- Returning a list of length n instead of n + 1, losing the count for n itself.
- Writing
ans[i >> 1] + i & 1without brackets; in most languages+binds tighter than&. - Reaching for a built-in bit count, which the problem asks you to avoid and which skips the idea being tested.
How to talk through it
- 1Clarify. Is n included? May I use a built-in bit count? Is O(n) expected?
- 2Give the simple count. Shift each number and count its bits: O(n log n).
- 3Reuse smaller answers.
i >> 1is i without its last bit and is already counted, so addi & 1to it. - 4Code the loop. Fill ans from 1 to n with
ans[i >> 1] + (i & 1); mention the brackets. - 5Test out loud. Check n = 0, a power of two and 15.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?