Problem overview
The function countBits receives an Int named n and returns an IntArray of n + 1 numbers. Element i of the result is the number of 1 bits in the binary form of i, for every i from 0 to n.
For n = 5 the numbers are 0, 1, 10, 11, 100 and 101 in binary, so the answer is [0, 1, 1, 2, 1, 2]. For n = 0 the only number is 0, which has no 1 bits, so the answer is [0].
Approach: reuse a smaller answer
Counting the bits of each number separately would work, but the statement asks for O(n) time, a constant amount of work per number. That is possible because every answer can be built from an earlier one.
Shifting a number one place to the right drops its last bit. For example, 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. The last bit is i and 1: 1 when i is odd and 0 when it is even.
That gives the rule bits[i] = bits[i shr 1] + (i and 1). Because i shr 1 is smaller than i, its count is already in the array if we fill it from 0 upward. This is dynamic programming: each answer comes from a smaller one that was computed earlier.
Step by step
- Create
bits, anIntArrayof sizen + 1, as aval. A newIntArrayis filled with zeros, and 0 has no 1 bits, sobits[0]is already right. The loop changes elements, not the array reference, sovalis fine. - Loop
iover1..n. Counting up matters, since each number needs a smaller one that is already filled in. The range1..nincludesn, and it is empty whennis 0. - Apply the rule:
bits[i] = bits[i shr 1] + (i and 1). - Return
bits.
The solution in Kotlin
class Solution {
fun countBits(n: Int): IntArray {
val bits = IntArray(n + 1)
for (i in 1..n) {
bits[i] = bits[i shr 1] + (i and 1)
}
return bits
}
}
For n = 5, each step looks like this:
i binary i shr 1 i and 1 bits[i]
0 0 0 0 0
1 1 0 1 1
2 10 1 0 1
3 11 1 1 2
4 100 2 0 1
5 101 2 1 2
The Kotlin details worth knowing:
- Bit operators are words.
shrshifts right andandis the bitwise AND. They are infix functions onInt. - Keep the parentheses around
i and 1. Named infix functions bind more loosely than+. Withi = 2,i and 1 + 1is evaluated as2 and 2and gives 2, while(i and 1) + 1gives 1. 1..nis inclusive at both ends, unlike0 until n.
Complexity
Time: O(n). Each number from 1 to n takes one step with one shift, one AND and one addition.
Space: O(1) extra, apart from the array the function returns. Only the loop variable is added.
Edge cases and common mistakes
n = 0. The loop doesn't run and the result is[0]. The array size isn + 1, notn.- Size
ninstead ofn + 1. The last write,bits[n], would be out of bounds and throwArrayIndexOutOfBoundsException. - Filling in the wrong direction. Going from
ndown would read entries that haven't been computed yet and see zeros. - Counting each number separately with a loop over its bits gives the right answer but spends extra work on every number.
Testing
n = 2gives[0, 1, 1].n = 5gives[0, 1, 1, 2, 1, 2].n = 0gives[0].n = 10gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2].
