Problem overview
The method countBits(_ n: Int) -> [Int] returns an array of n + 1 numbers in which 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, 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 lesson asks for O(n) time, which means a constant amount of work per number, and no extra space beyond the returned array.
Approach: reuse the answer for a smaller number
Counting the bits of each number separately would cost a loop of up to about 17 steps per number for these inputs. A faster way notices that every number is related to a smaller one.
Shifting a number one place to the right drops its last bit. 13 is 1101, and shifted right it is 110, which is 6. So 13 has exactly the 1 bits of 6, plus its own last bit. That last bit is i & 1: 1 when i is odd, 0 when it is even.
This gives a rule: bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 is smaller than i (for i of 1 or more), filling the array from low to high guarantees that the entry it needs is already there. Each number then takes one step. This is dynamic programming: each answer is built from an earlier one.
For 13, the lookup reads bits[6], which is 2, and adds 13 & 1, which is 1, for a total of 3. A real run gives 13 >> 1 = 6, 13 & 1 = 1, bits[6] = 2 and bits[13] = 3.
Step by step
- Create
bitsasn + 1zeros with[Int](repeating: 0, count: n + 1). It is avarbecause the loop fills it. Entry 0 is already right, since 0 has no 1 bits. - Loop
iover1..<(n + 1), from 1 ton. Counting up matters: each number reuses a smaller one that must already be filled in. - Apply the rule:
bits[i] = bits[i >> 1] + (i & 1). The shift drops the last bit and the AND with 1 keeps only that bit. - Return
bits.
The solution in Swift
class Solution {
func countBits(_ n: Int) -> [Int] {
var bits = [Int](repeating: 0, count: n + 1)
for i in 1..<(n + 1) {
bits[i] = bits[i >> 1] + (i & 1)
}
return bits
}
}
The Swift details worth a closer look:
- Why
1..<(n + 1)and not1...n. A Swift range can't end before it starts. Withn = 0, the closed range1...0stops the program with a crash when it is created. The half-open1..<1is just an empty range, so the loop does nothing and the result is[0]. - Operators.
>>shifts bits right and&is bitwise AND. In Swift,&binds tighter than+, so the parentheses in(i & 1)aren't required, but they make the line easier to read. [Int](repeating:count:). It builds an array with the given number of copies of a value. Herecountisn + 1because the array holds the numbers 0 ton.- Mutable array. Assigning to
bits[i]requiresvar. Withletthe compiler reports an error.
Tracing n = 5
The loop fills the array from the left, and each entry uses an earlier one. The results for a few values of n:
2 [0, 1, 1]
5 [0, 1, 1, 2, 1, 2]
13 [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3]
For i = 4 the rule reads bits[2] + 0, which is 1. For i = 5 it reads bits[2] + 1, which is 2.
Complexity
Time: O(n). The loop runs n times and each pass does a shift, an AND, an addition and two array accesses.
Space: O(1) beyond the output. The returned array holds n + 1 numbers, and the loop adds only the variable i.
Edge cases and common mistakes
n = 0. The result is[0]. The half-open range keeps the loop from running.n = 1. The result is[0, 1].- Array of the wrong size. The array needs
n + 1entries. Withnentries, the write tobits[n]is out of range and crashes. - Looping downward or out of order. The rule needs
bits[i >> 1]to be filled already, so the loop must go upward. - Dropping the last bit. Using only
bits[i >> 1]undercounts every odd number by one. - Big inputs. For
n = 100000the result has 100001 entries, and the largest count in it is 16, at 65535.
Testing
n = 2gives[0, 1, 1].n = 5gives[0, 1, 1, 2, 1, 2].n = 0gives[0].n = 1gives[0, 1].n = 16gives[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1].
