Start learning free

LESSON 305 OF 314 · BIT MANIPULATION

Counting Bits in C++: O(n) with bits[i >> 1]

Practice O(n) Read the full explanation

You get a whole number n.

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

    C++ · BIT MANIPULATION

    Counting Bits in C++, explained

    Problem overview

    The method countBits takes an integer n and returns a vector<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, 101 in binary, so the answer is [0, 1, 1, 2, 1, 2]. For n = 0 the answer is [0].

    The statement asks for O(n) time, a constant amount of work per number, and no extra space besides the returned vector.

    Approach: reuse the count of a smaller number

    Counting the bits of every number separately costs up to about 17 steps each for values up to 100,000, and it ignores a pattern: the answers are related. Shifting a number right by one place drops its last bit. So i has the same 1 bits as i >> 1, plus its own last bit, which is i & 1: 1 for an odd number and 0 for an even one.

    That gives the recurrence bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 is smaller than i, its count is already in the vector when we reach i, as long as we fill the vector from 0 upward. bits[0] is 0 and needs no work.

    For example, 13 is 1101. Shifted right it is 110, which is 6, with two 1 bits. The last bit of 13 is 1, so 13 has three. The lesson's code for n = 13 returns:

    0 1 1 2 1 2 2 3 1 2 2 3 2 3
    

    The entry at index 6 is 2 and the entry at index 13 is 3, as computed above.

    Step by step

    1. Create bits with n + 1 zeros: one slot for each number from 0 to n. Zero has no 1 bits, so bits[0] is already right.
    2. Loop from 1 to n inclusive. The order is upward, so each number finds the smaller one's answer already stored.
    3. Apply the recurrence: bits[i] = bits[i >> 1] + (i & 1).
    4. Return bits.

    The solution in C++

    class Solution {
    public:
        vector<int> countBits(int n) {
            vector<int> bits(n + 1, 0);
            for (int i = 1; i <= n; i++) {
                bits[i] = bits[i >> 1] + (i & 1);
            }
            return bits;
        }
    };
    

    C++ details worth knowing:

    • Size and value. vector<int> bits(n + 1, 0) makes n + 1 elements, each 0. Valid indices run from 0 to n, so the loop condition is i <= n, not i < n.
    • Parentheses around i & 1. The operator & binds more loosely than +, so bits[i >> 1] + i & 1 would mean (bits[i >> 1] + i) & 1, a different number.
    • >> on a non-negative int divides by 2 and rounds down, so i >> 1 is the same as i / 2 here.
    • Returning by value. Returning the local vector doesn't copy it element by element; the compiler moves it or builds it in place.

    Complexity

    Time: O(n). The loop runs n times and each pass does a shift, an AND, an addition and one lookup.

    Space: O(1) extra. Apart from the vector that is returned, only the loop variable is kept.

    Edge cases and common mistakes

    • n = 0. The vector has one element, 0, and the loop doesn't run. The answer is [0].
    • Stopping one short. With i < n the last entry stays 0. For n = 5 that would give [0, 1, 1, 2, 1, 0].
    • Filling downward. The recurrence needs the smaller number's answer first, so the loop must go upward.
    • Forgetting the last bit. bits[i >> 1] alone is off by one for every odd i.

    Testing

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