Start learning free

LESSON 589 OF 671 · BIT MANIPULATION

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

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

    JAVASCRIPT · BIT MANIPULATION

    Counting Bits in JavaScript, explained

    Problem overview

    The method countBits(n) returns an array of n + 1 numbers. Position i holds 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 O(1) extra space besides the returned array.

    Approach: reuse the answer for a smaller number

    You could count the bits of every number separately, which costs up to about 17 steps per number for n up to 100,000. A better way notices that the answers are related.

    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. In general:

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

    The number i >> 1 is smaller than i, so if you fill the array from the bottom up, its count is already there. The expression i & 1 keeps only the last bit: 1 for odd numbers, 0 for even ones. This is dynamic programming: each answer is built from a smaller, already computed one.

    Here is the array filled for n = 10:

    [0,1,1,2,1,2,2,3,1,2,2]
    

    Number 6 (110) has two 1 bits because 3 (11) has two and 6 is even. Number 7 (111) has three because 3 has two and 7 is odd.

    Step by step

    1. Create bits with new Array(n + 1).fill(0), declared with const. Zero has no 1 bits, so bits[0] is already correct.
    2. Loop from 1 up to n with let i. Counting upward matters, since each number needs the count of a smaller one.
    3. Set bits[i] to bits[i >> 1] + (i & 1).
    4. Return bits.

    The solution in JavaScript

    class Solution {
        /**
        * @param {number} n
        * @return {number[]}
        */
        countBits(n) {
            const bits = new Array(n + 1).fill(0);
            for (let i = 1; i <= n; i++) {
                bits[i] = bits[i >> 1] + (i & 1);
            }
            return bits;
        }
    }
    

    JavaScript details to know:

    • Keep the parentheses around i & 1. The operator + binds tighter than &, so bits[i >> 1] + i & 1 would add first and then AND the sum with 1. For i = 5, bits[2] + 5 & 1 is 6 & 1, which is 0, while the correct term gives 2.
    • new Array(n + 1).fill(0) creates an array with n + 1 slots all set to 0. Without fill, the slots are empty holes and reading them gives undefined, which would turn the sums into NaN.
    • >> works on 32-bit integers. The result of 13 >> 1 is 6, the same as halving and rounding down for non-negative numbers. For the lesson's range (up to 100,000) that is exact.

    Complexity

    Time: O(n). The loop runs n times and each pass does a constant amount of work: one shift, one AND, one addition and an array read and write.

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

    Edge cases and common mistakes

    • n = 0. The array has one element and the loop never runs, so the result is [0].
    • Powers of two. Numbers such as 1, 2, 4, 8 and 16 each have a single 1 bit. For n = 16 the result ends with ..., 3, 4, 1]: the entry for 16 is 1.
    • Size of the array. It needs n + 1 entries, not n, because 0 and n are both included.
    • Looping downward or starting at 0. Starting at 0 is harmless, since 0 >> 1 is 0, but going downward reads entries that haven't been filled yet.
    • Counting bits with toString(2). Converting each number to a binary string and counting the '1' characters is correct but allocates a string per number. The shift approach avoids it.

    Testing

    • n = 0 gives [0].
    • n = 1 gives [0, 1].
    • n = 2 gives [0, 1, 1].
    • n = 5 gives [0, 1, 1, 2, 1, 2].
    • n = 10 gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2].
    • n = 16 gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1].
    • n = 100000 returns an array of 100001 entries whose last value is 6, and every entry matches a bit-by-bit count.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free