<AI/>
enru
All posts

Counting bits

LeetCode 338: Count the number of 1 bits for every number from 0 to n using pop count or dynamic programming.

Difficulty
Easy
Published
Topics
#bit manipulation#dynamic programming
Open on LeetCode

Problem Description

You are given a number n.

Return an array ans of length n + 1, where the value of each i-th element equals the number of ones in the binary representation of i, for every i from 0 to n.

Constraints

  • n is in the range from 1 to 105

Examples

Input: n = 2

Answer: [0, 1, 1]

Explanation:

Binary representations of the numbers:

0 --> 0
1 --> 1
2 --> 10

Pop Count approach

We can reuse the population count approach from the Number of 1 bits problem.

All we need is to call hammingWeight to compute the Hamming weight in a loop from 0 to n.

typescript
const hammingWeight = (n: number): number => {
  let count = 0;
 
  while (n != 0) {
    count++;
    n &= n - 1;
  }
 
  return count;
};
 
export const countBitsPopCount = (n: number): number[] => {
  const res: number[] = [];
 
  for (let i = 0; i <= n; i++) {
    res.push(hammingWeight(i));
  }
 
  return res;
};

Complexity Analysis

Time Complexity

From the previous problem we know that hammingWeight runs in O(1). Since the function is called n times, the overall complexity is O(n).

Space Complexity

O(n), since we allocate memory for the result array.

Dynamic programming approach

There's a simpler way to solve the problem, but you need to know the formula or figure out the pattern in the number of ones in the binary representation of a number. There are several such formulas, and we'll use the simplest one.

F(x) = F(x/2) + (x mod 2)

This formula says that to get the number of ones in the binary representation of x, we can take the number of ones in the binary representation of x/2 and add the remainder of dividing x by 2.

Now let's rewrite the formula in terms of bit operations:

  • x / 2 is equivalent to a right shift by one bit, i.e. x >> 1
  • x mod 2 is equivalent to taking the lowest bit, i.e. x & 1

The general idea

We can think of a number i as i >> 1 with one more bit appended at the end. If the last bit is one, the total number of ones is one more than for i >> 1; if the last bit is zero, the number of ones is the same as for i >> 1.

We count the ones for every number from 0 to n and store each result in the result array res. On each iteration we can rely on the results of previous iterations and take the value for i >> 1 from the result array, since it has already been computed.

typescript
export const countBits = (n: number): number[] => {
  const res: number[] = [];
 
  for (let i = 0; i <= n; i++) {
    res[i] = (res[i >> 1] ?? 0) + (i & 1);
  }
 
  return res;
};

Complexity Analysis

Time Complexity

O(n), since we perform one computation for each number.

Space Complexity

O(n), since we allocate memory for the result array.