Start learning free

LESSON 305 OF 314 · BIT MANIPULATION

Counting Bits in Swift: Dynamic Programming in O(n)

Practice O(n) Read the full explanation

You get a whole number n.

Return an array bits with n + 1 numbers. For each i, bits[i] is how many 1s the number i has in binary.

 

Example 1:

Input: n = 4
Output: [0,1,1,2,1]
Explanation: Each number in binary:
0 is 0, with no 1s.
1 is 1, with one 1.
2 is 10, with one 1.
3 is 11, with two 1s.
4 is 100, with one 1.

Example 2:

Input: n = 8
Output: [0,1,1,2,1,2,2,3,1]
Explanation: 7 is 111 in binary, so it has three 1s.
8 is 1000, so it has one 1.

Example 3:

Input: n = 0
Output: [0]
Explanation: The only number is 0, and it has no 1s.

 

Constraints:

  • n is from 0 to 100,000.
Note:

Your algorithm should run in O(n) time, a constant amount of work per number, and use O(1) extra space besides the array it returns.



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.

Fill the answer from 0 up to n. When you reach i, the count of i shifted right by one is already in the array, because that number is smaller than i. Add the last bit of i, which is i AND 1: 1 when i is odd, 0 when it is even.

Each number from 1 to n takes one step: O(n) time.
Apart from the array we return, we keep only the loop variable, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · BIT MANIPULATION

    Counting Bits in Swift, explained

    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

    1. Create bits as n + 1 zeros with [Int](repeating: 0, count: n + 1). It is a var because the loop fills it. Entry 0 is already right, since 0 has no 1 bits.
    2. Loop i over 1..<(n + 1), from 1 to n. Counting up matters: each number reuses a smaller one that must already be filled in.
    3. 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.
    4. 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 not 1...n. A Swift range can't end before it starts. With n = 0, the closed range 1...0 stops the program with a crash when it is created. The half-open 1..<1 is 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. Here count is n + 1 because the array holds the numbers 0 to n.
    • Mutable array. Assigning to bits[i] requires var. With let the 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 + 1 entries. With n entries, the write to bits[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 = 100000 the result has 100001 entries, and the largest count in it is 16, at 65535.

    Testing

    • n = 2 gives [0, 1, 1].
    • n = 5 gives [0, 1, 1, 2, 1, 2].
    • n = 0 gives [0].
    • n = 1 gives [0, 1].
    • n = 16 gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free