Start learning free

LESSON 591 OF 673 · BIT MANIPULATION

Counting Bits in Python: O(n) with Dynamic Programming

Practice O(n) Read the full explanation

You get a whole number n.

Return a list 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 list 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 list, 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 list we return, we keep only the loop variable, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · BIT MANIPULATION

    Counting Bits in Python, explained

    Problem overview

    The method countBits receives an integer n and returns a list of n + 1 numbers. The entry at index 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, with 0, 1, 1, 2, 1 and 2 one bits. The result is [0, 1, 1, 2, 1, 2]. For n = 0 the result is [0].

    The lesson asks for O(n) time, a constant amount of work per number, and O(1) extra space besides the list it returns.

    Approach: reuse the answer for a smaller number

    You could count the bits of each number on its own. That costs one step per bit of each number, so about n log n steps in all. There is a faster way, because the answers for neighbouring numbers are closely related.

    Shifting a number one place to the right drops its last bit. For example, 13 is 1101, and shifted right it becomes 110, which is 6. So 13 has exactly the 1 bits of 6, plus its own last bit. That last bit is 1 when the number is odd and 0 when it is even, and i & 1 reads it.

    In other words, for every i:

    bits[i] = bits[i >> 1] + (i & 1)
    

    The number i >> 1 is smaller than i (for i of at least 1), so if you fill the list from small numbers to large ones, its answer is already there when you need it. Each entry takes one lookup, one shift, one AND and one addition.

    Step by step

    1. Create the list. bits = [0] * (n + 1) makes n + 1 zeros. Index 0 is already correct, because 0 has no 1 bits.
    2. Loop upward from 1. for i in range(1, n + 1) goes from 1 to n. Counting up matters: each number uses the entry of a smaller one, which must be filled in first.
    3. Fill each entry. Set bits[i] to bits[i >> 1] + (i & 1). The shift drops the last bit and the AND keeps only that bit.
    4. Return bits after the loop.

    The solution in Python

    class Solution:
        def countBits(self, n: int) -> List[int]:
            bits = [0] * (n + 1)
            for i in range(1, n + 1):
                bits[i] = bits[i >> 1] + (i & 1)
            return bits
    

    Python details worth knowing

    • range(1, n + 1) stops before its second value. The upper end is excluded, so n + 1 is needed to include n. For n = 0 the range is empty and the loop does nothing.
    • Keep the parentheses around i & 1. & binds more loosely than +, so without them bits[i >> 1] + i & 1 means (bits[i >> 1] + i) & 1, a very different value.
    • [0] * (n + 1) is safe for numbers. Integers are immutable, so assigning to one slot doesn't affect the others.
    • >> 1 on a non-negative integer is the same as // 2. The shift says what you mean: dropping the last bit.

    The pattern in the output

    Running the solution gives these results:

    nResult
    0[0]
    2[0, 1, 1]
    5[0, 1, 1, 2, 1, 2]
    10[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]

    Take i = 5 in the last row. Its binary form is 101. Shifting right gives 10, which is 2, and bits[2] is 1. The last bit of 5 is 1, so bits[5] = 1 + 1 = 2. For i = 8 (1000), shifting gives 4 (100), with one bit, and the last bit is 0, so bits[8] stays 1.

    Complexity

    Time: every number from 1 to n takes one step, with a constant amount of work, so the time is O(n).

    Space: apart from the list that is returned, only the loop variable is kept, so the extra space is O(1).

    Edge cases and common mistakes

    • n = 0. The list is [0] and the loop is skipped.
    • Off-by-one in the length. The list needs n + 1 entries, because it covers 0 through n. A list of n zeros would raise an IndexError at bits[n].
    • Looping downward. The entry at i depends on a smaller index, so the loop must go up. Going down would read entries that are still 0.
    • Missing parentheses. As shown above, dropping them around i & 1 changes the result.
    • Counting each number from scratch. A nested loop that counts bits per number gives correct results but takes longer than the lesson allows.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free