Problem overview
The method countBits(n) returns an array of n + 1 numbers. Position i holds 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, so the answer is [0, 1, 1, 2, 1, 2]. For n = 0 the answer is [0].
The statement 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
You could count the bits of every number separately, which costs up to about 17 steps per number for n up to 100,000. A better way notices that the answers are related.
Shifting a number one place to the right drops its last bit. 13 is 1101 and 13 shifted right is 110, which is 6. So 13 has the 1 bits of 6, plus its own last bit. In general:
bits[i] = bits[i >> 1] + (i & 1)
The number i >> 1 is smaller than i, so if you fill the array from the bottom up, its count is already there. The expression i & 1 keeps only the last bit: 1 for odd numbers, 0 for even ones. This is dynamic programming: each answer is built from a smaller, already computed one.
Here is the array filled for n = 10:
[0,1,1,2,1,2,2,3,1,2,2]
Number 6 (110) has two 1 bits because 3 (11) has two and 6 is even. Number 7 (111) has three because 3 has two and 7 is odd.
Step by step
- Create
bitswithnew Array(n + 1).fill(0), declared withconst. Zero has no 1 bits, sobits[0]is already correct. - Loop from 1 up to
nwithlet i. Counting upward matters, since each number needs the count of a smaller one. - Set
bits[i]tobits[i >> 1] + (i & 1). - Return
bits.
The solution in JavaScript
class Solution {
/**
* @param {number} n
* @return {number[]}
*/
countBits(n) {
const bits = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
}
JavaScript details to know:
- Keep the parentheses around
i & 1. The operator+binds tighter than&, sobits[i >> 1] + i & 1would add first and then AND the sum with 1. Fori = 5,bits[2] + 5 & 1is6 & 1, which is 0, while the correct term gives 2. new Array(n + 1).fill(0)creates an array withn + 1slots all set to 0. Withoutfill, the slots are empty holes and reading them givesundefined, which would turn the sums intoNaN.>>works on 32-bit integers. The result of13 >> 1is 6, the same as halving and rounding down for non-negative numbers. For the lesson's range (up to 100,000) that is exact.
Complexity
Time: O(n). The loop runs n times and each pass does a constant amount of work: one shift, one AND, one addition and an array read and write.
Space: O(1) extra. Apart from the array that is returned, only the loop variable is stored.
Edge cases and common mistakes
n = 0. The array has one element and the loop never runs, so the result is[0].- Powers of two. Numbers such as 1, 2, 4, 8 and 16 each have a single 1 bit. For
n = 16the result ends with..., 3, 4, 1]: the entry for 16 is 1. - Size of the array. It needs
n + 1entries, notn, because 0 andnare both included. - Looping downward or starting at 0. Starting at 0 is harmless, since
0 >> 1is 0, but going downward reads entries that haven't been filled yet. - Counting bits with
toString(2). Converting each number to a binary string and counting the'1'characters is correct but allocates a string per number. The shift approach avoids it.
Testing
n = 0gives[0].n = 1gives[0, 1].n = 2gives[0, 1, 1].n = 5gives[0, 1, 1, 2, 1, 2].n = 10gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2].n = 16gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1].n = 100000returns an array of 100001 entries whose last value is6, and every entry matches a bit-by-bit count.
