Problem overview
The method countBits receives an integer n and returns an array of n + 1 numbers. The element at index i, for every i from 0 to n, is the number of 1 bits in the binary form of i.
For n = 5 the numbers are 0, 1, 10, 11, 100 and 101 in binary, so the result is [0, 1, 1, 2, 1, 2]. For n = 0 the only number is 0, which has no 1 bits, so the result is [0].
The note asks for O(n) time, a constant amount of work per number, and O(1) extra space besides the returned array.
Approach: reuse the answer for a smaller number
Counting the bits of each number separately would cost up to about 17 steps per number for values up to 100,000. The faster idea is that every number is built from a smaller one plus a single bit.
Shifting a number right by one place, i >> 1, drops its last bit. For i = 13, which is 1101, i >> 1 is 110, which is 6. So 13 has all the 1 bits of 6, plus its own last bit. That last bit is i & 1: 1 when i is odd and 0 when it is even.
The relation is bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 is smaller than i, its count is already in the array if we fill it from the smallest number upward. The base case, bits[0] = 0, is free because the array starts as zeros. This is a small example of dynamic programming: each answer is computed from earlier answers.
Step by step
- Create
bitswithnew Array(n + 1).fill(0). It has one slot for every number from 0 ton, andbits[0]is already correct. - Loop
ifrom 1 ton, counting up. Each number reuses the count of a smaller one, which must be filled in by then. - Apply the relation:
bits[i] = bits[i >> 1] + (i & 1). - Return
bits.
The solution in TypeScript
class Solution {
countBits(n: number): number[] {
const bits: number[] = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
}
For n = 10 the method returns [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]. Taking i = 13 as an example: 13 >> 1 is 6, which has two 1 bits, and 13 & 1 is 1, so 13 has three.
Some TypeScript details:
- Parentheses around
i & 1. Inbits[i >> 1] + i & 1, the+is evaluated first, and the whole sum is then ANDed with 1. Withx = 3andy = 4,x + y & 1is1butx + (y & 1)is3. >> 1is not/ 2in general.numberdivision gives fractions:7 / 2is3.5, while7 >> 1is3. For the non-negative values here the shift matchesMath.floor(i / 2).- Bitwise operators use 32-bit integers. That is plenty for
nup to 100,000. new Array(n + 1).fill(0)creates the empty slots and fills each with the number 0. Withoutfill, the slots would be empty and the additions would produceNaN.- Types are erased.
number[]is only for the compiler, andfill(0)is what really puts numbers in the array.
Complexity
Time: O(n). The loop runs n times and each pass does one shift, one AND, one addition and one array read and write.
Space: O(1) extra. Apart from the n + 1 numbers of the returned array, the method keeps only the loop variable.
Edge cases and common mistakes
n = 0. The array has one element, the loop doesn't run, and the result is[0].n = 1. The result is[0, 1].- Array size. The array needs
n + 1elements, because both 0 andnare included. Withnelements, the last assignment would add an extra element beyond the intended length. - Starting the loop at 0. It would be harmless here, since
bits[0]becomesbits[0] + 0, but starting at 1 matches the base case. - Counting downward. Filling from
ndown would read entries that are still 0. - Largest input. For
n = 100000the array has 100,001 elements, andbits[100000]is 6.
Testing
n = 2gives[0, 1, 1].n = 5gives[0, 1, 1, 2, 1, 2].n = 0gives[0].n = 1gives[0, 1].n = 10gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2].n = 15gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4].
