Start learning free

LESSON 305 OF 314 · BIT MANIPULATION

Counting Bits in TypeScript: O(n) with a Shift and 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

    TYPESCRIPT · BIT MANIPULATION

    Counting Bits in TypeScript, explained

    Problem overview

    The method countBits receives an integer n and returns an array of n + 1 numbers. The element at index i, for every i from 0 to n, is the number of 1 bits in the binary form of i.

    For n = 5 the numbers are 0, 1, 10, 11, 100 and 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 note 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

    Counting the bits of each number separately would cost up to about 17 steps per number for values up to 100,000. The faster idea is that every number is built from a smaller one plus a single bit.

    Shifting a number right by one place, i >> 1, drops its last bit. For i = 13, which is 1101, i >> 1 is 110, which is 6. So 13 has all the 1 bits of 6, plus its own last bit. That last bit is i & 1: 1 when i is odd and 0 when it is even.

    The relation is bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 is smaller than i, its count is already in the array if we fill it from the smallest number upward. The base case, bits[0] = 0, is free because the array starts as zeros. This is a small example of dynamic programming: each answer is computed from earlier answers.

    Step by step

    1. Create bits with new Array(n + 1).fill(0). It has one slot for every number from 0 to n, and bits[0] is already correct.
    2. Loop i from 1 to n, counting up. Each number reuses the count of a smaller one, which must be filled in by then.
    3. Apply the relation: bits[i] = bits[i >> 1] + (i & 1).
    4. Return bits.

    The solution in TypeScript

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

    For n = 10 the method returns [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]. Taking i = 13 as an example: 13 >> 1 is 6, which has two 1 bits, and 13 & 1 is 1, so 13 has three.

    Some TypeScript details:

    • Parentheses around i & 1. In bits[i >> 1] + i & 1, the + is evaluated first, and the whole sum is then ANDed with 1. With x = 3 and y = 4, x + y & 1 is 1 but x + (y & 1) is 3.
    • >> 1 is not / 2 in general. number division gives fractions: 7 / 2 is 3.5, while 7 >> 1 is 3. For the non-negative values here the shift matches Math.floor(i / 2).
    • Bitwise operators use 32-bit integers. That is plenty for n up to 100,000.
    • new Array(n + 1).fill(0) creates the empty slots and fills each with the number 0. Without fill, the slots would be empty and the additions would produce NaN.
    • Types are erased. number[] is only for the compiler, and fill(0) is what really puts numbers in the array.

    Complexity

    Time: O(n). The loop runs n times and each pass does one shift, one AND, one addition and one array read and write.

    Space: O(1) extra. Apart from the n + 1 numbers of the returned array, the method keeps only the loop variable.

    Edge cases and common mistakes

    • n = 0. The array has one element, the loop doesn't run, and the result is [0].
    • n = 1. The result is [0, 1].
    • Array size. The array needs n + 1 elements, because both 0 and n are included. With n elements, the last assignment would add an extra element beyond the intended length.
    • Starting the loop at 0. It would be harmless here, since bits[0] becomes bits[0] + 0, but starting at 1 matches the base case.
    • Counting downward. Filling from n down would read entries that are still 0.
    • Largest input. For n = 100000 the array has 100,001 elements, and bits[100000] is 6.

    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 = 10 gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2].
    • n = 15 gives [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free