Problem overview
The method countBits receives an integer n and returns a list of n + 1 numbers. The entry at index i is the number of 1 bits in the binary form of i, for every i from 0 to n.
For n = 5 the numbers 0 to 5 are 0, 1, 10, 11, 100, 101 in binary, with 0, 1, 1, 2, 1 and 2 one bits. The result is [0, 1, 1, 2, 1, 2]. For n = 0 the result is [0].
The lesson asks for O(n) time, a constant amount of work per number, and O(1) extra space besides the list it returns.
Approach: reuse the answer for a smaller number
You could count the bits of each number on its own. That costs one step per bit of each number, so about n log n steps in all. There is a faster way, because the answers for neighbouring numbers are closely related.
Shifting a number one place to the right drops its last bit. For example, 13 is 1101, and shifted right it becomes 110, which is 6. So 13 has exactly the 1 bits of 6, plus its own last bit. That last bit is 1 when the number is odd and 0 when it is even, and i & 1 reads it.
In other words, for every i:
bits[i] = bits[i >> 1] + (i & 1)
The number i >> 1 is smaller than i (for i of at least 1), so if you fill the list from small numbers to large ones, its answer is already there when you need it. Each entry takes one lookup, one shift, one AND and one addition.
Step by step
- Create the list.
bits = [0] * (n + 1)makesn + 1zeros. Index 0 is already correct, because 0 has no 1 bits. - Loop upward from 1.
for i in range(1, n + 1)goes from 1 ton. Counting up matters: each number uses the entry of a smaller one, which must be filled in first. - Fill each entry. Set
bits[i]tobits[i >> 1] + (i & 1). The shift drops the last bit and the AND keeps only that bit. - Return
bitsafter the loop.
The solution in Python
class Solution:
def countBits(self, n: int) -> List[int]:
bits = [0] * (n + 1)
for i in range(1, n + 1):
bits[i] = bits[i >> 1] + (i & 1)
return bits
Python details worth knowing
range(1, n + 1)stops before its second value. The upper end is excluded, son + 1is needed to includen. Forn = 0the range is empty and the loop does nothing.- Keep the parentheses around
i & 1.&binds more loosely than+, so without thembits[i >> 1] + i & 1means(bits[i >> 1] + i) & 1, a very different value. [0] * (n + 1)is safe for numbers. Integers are immutable, so assigning to one slot doesn't affect the others.>> 1on a non-negative integer is the same as// 2. The shift says what you mean: dropping the last bit.
The pattern in the output
Running the solution gives these results:
| n | Result |
|---|---|
| 0 | [0] |
| 2 | [0, 1, 1] |
| 5 | [0, 1, 1, 2, 1, 2] |
| 10 | [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2] |
Take i = 5 in the last row. Its binary form is 101. Shifting right gives 10, which is 2, and bits[2] is 1. The last bit of 5 is 1, so bits[5] = 1 + 1 = 2. For i = 8 (1000), shifting gives 4 (100), with one bit, and the last bit is 0, so bits[8] stays 1.
Complexity
Time: every number from 1 to n takes one step, with a constant amount of work, so the time is O(n).
Space: apart from the list that is returned, only the loop variable is kept, so the extra space is O(1).
Edge cases and common mistakes
n = 0. The list is[0]and the loop is skipped.- Off-by-one in the length. The list needs
n + 1entries, because it covers 0 throughn. A list ofnzeros would raise anIndexErroratbits[n]. - Looping downward. The entry at
idepends on a smaller index, so the loop must go up. Going down would read entries that are still 0. - Missing parentheses. As shown above, dropping them around
i & 1changes the result. - Counting each number from scratch. A nested loop that counts bits per number gives correct results but takes longer than the lesson allows.
