Counting Bits
Count the 1 bits of every number from 0 to n, reusing the answer for the number with its last bit dropped.
The problem
You get an integer n. Return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i. Aim for a single pass that is O(n) in total.
Input n = 7
Output [0, 1, 1, 2, 1, 2, 2, 3]
7 is 111, so the last count is 3; 6 is 110, so the one before it is 2.
Input n = 0
Output [0]
0 has no 1 bits.
Key constraint: n can be 100,000, and the goal is O(n) time, so counting the bits of every number from scratch, O(n log n), is not the target.
How to spot the pattern
- You need an answer for every number in a range, and bigger numbers are built from smaller ones.
- Shifting right by one turns
iinto a smaller number whose answer you already have.
The idea
State: bits[i] is the number of 1 bits in i. Shifting i right by one drops its last bit and gives i >> 1, a smaller number whose count is already known, so bits[i] = bits[i >> 1] + (i & 1). Filling the array from 1 upward, every value costs one lookup and one addition.
Brute force: Count the bits of each number on its own, which takes O(n log n) time.
Step by step
- 1Make
bitsof sizen + 1withbits[0] = 0. - 2For each
ifrom 1 ton, setbits[i] = bits[i >> 1] + (i & 1). - 3Return
bits.
Code
class Solution:
def countBits(self, n: int) -> List[int]:
# i has the same 1 bits as i >> 1 (i with its last bit dropped), plus its last bit
bits = [0] * (n + 1)
for i in range(1, n + 1):
bits[i] = bits[i >> 1] + (i & 1)
return bitsComplexity
Time
O(n)
Space
O(n)
One constant-time step per number; the array is the answer itself.
Watch out for
- Writing
bits[i >> 1] + i & 1without brackets:+binds tighter than&, so the result is wrong. - Counting each number's bits separately, which works but misses the O(n) goal.
Follow-up questions
Is there another recurrence?
Yes: bits[i] = bits[i & (i - 1)] + 1, because i & (i - 1) is i with its lowest 1 bit cleared.
How does this relate to Number of 1 Bits?
That problem counts the bits of one number. Here the counts for all smaller numbers are already in the array, so each new number costs O(1).
In Hinglish
`i >> 1` matlab i ka aakhri bit hata diya, aur uska answer pehle se array mein hai. Bas aakhri bit `(i & 1)` jod do.