Problem overview
The method countBits(int n) returns an int[] of n + 1 numbers. Entry 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 and 101 in binary, so the result is [0, 1, 1, 2, 1, 2]. For n = 0 the result is [0].
The target is O(n) time, a constant amount of work per number, and no extra space beyond the returned array.
Approach: reuse the answer of a smaller number
Counting the bits of every number separately costs up to about 17 steps each for numbers up to 100,000. A faster way notices that the answers are related.
Shifting a number right by one, i >> 1, drops its last bit. The result is smaller than i (for i >= 1), so its bit count is already in the array if we fill it from the start. The number i itself has the same bits plus that last one, and the last bit is i & 1: 1 when i is odd and 0 when it is even. So:
bits[i] = bits[i >> 1] + (i & 1)
Take 13, which is 1101. Shifted right it is 110, which is 6 and has two 1 bits. The last bit of 13 is 1, so 13 has three. This is dynamic programming: each answer is built from an answer already stored.
For n = 5 the loop does this:
1 -> bits[0]=0 + 1 = 1
2 -> bits[1]=1 + 0 = 1
3 -> bits[1]=1 + 1 = 2
4 -> bits[2]=1 + 0 = 1
5 -> bits[2]=1 + 1 = 2
Step by step
- Create
bits, anint[]of sizen + 1. Java fills a newintarray with zeros, and 0 has no 1 bits, sobits[0]is already right. - Loop
ifrom 1 up to and includingn. Counting upward matters: each number reads the entry of a smaller one, which must already be filled. - Apply the rule:
bits[i] = bits[i >> 1] + (i & 1). - Return
bits.
The solution in Java
class Solution {
public int[] countBits(int n) {
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) {
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
}
The Java details worth a closer look:
- Keep the parentheses around
i & 1. Without thembits[i >> 1] + i & 1is read as(bits[i >> 1] + i) & 1, because+binds tighter than&. That is a different number, and wrong. - Array size. The array has
n + 1entries so that indexnexists. The loop'si <= nis the matching bound;i < nwould leave the last entry at 0. >>on positive numbers. For non-negativei,i >> 1is the same as dividing by 2 and dropping the remainder. Sinceiis never negative here, the sign-copying behaviour of>>doesn't come into play.- Indexing with an expression.
bits[i >> 1]uses the shift result directly as an index. No cast is needed because it is already anint.
Complexity
Time: O(n). Each of the n iterations does one shift, one AND, one addition and one array read and write.
Space: O(1) extra. The only memory is the returned array of n + 1 numbers, which the task requires anyway.
Edge cases and common mistakes
n = 0. The array has one entry, the loop starts at 1 and doesn't run, and the result is[0].- Starting the loop at 0. Not harmful here:
bits[0 >> 1] + (0 & 1)isbits[0] + 0. Starting at 1 just skips a pointless step. - Counting downward. A loop from
nto 1 would read entries that haven't been filled yet, and they would still be 0. - Dropping the parentheses. This is the classic slip, and it gives wrong values without any error message.
- Off by one in the size.
new int[n]makes indexninvalid, and the loop throws anArrayIndexOutOfBoundsExceptionwhen it reaches it.
Testing
n = 0gives[0].n = 2gives[0, 1, 1].n = 5gives[0, 1, 1, 2, 1, 2].n = 13gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3].
