Counting Bits

Difficulty: Easy

Given a non-negative number n, count the 1 bits in every number from 0 to n. Return the counts as a list, where position i holds the count for i.

Examples

Input: n = 2
Output: [0, 1, 1]

0 is 0b0 (zero 1 bits). 1 is 0b1 (one 1 bit). 2 is 0b10 (one 1 bit).

Input: n = 5
Output: [0, 1, 1, 2, 1, 2]

0=0b0, 1=0b1, 2=0b10, 3=0b11 (two 1 bits), 4=0b100 (one 1 bit), 5=0b101 (two 1 bits).

Constraints

  • 0 <= n <= 10^5

Approach

The direct way counts the 1 bits of each number from 0 to n on its own. It's correct, but it redoes work that was already done for smaller numbers.

A cheaper way reuses earlier answers. i >> 1 drops i's last bit and equals Math.floor(i / 2), a smaller number you've already counted. So i's count is that number's count, plus 1 if the dropped bit (i & 1) was 1.

This fills a table of answers in one pass, with no recomputing.

Solutions

Brute Force - Count Each Number Independently

For each number from 0 to n, count its 1 bits from scratch with a bit-by-bit check (or the 'clear the lowest set bit' trick).

function countBits(n) {
  const result = new Array(n + 1).fill(0);

  for (let i = 0; i <= n; i++) {
    let num = i;
    let count = 0;
    while (num > 0) {
      count += num & 1;
      num = num >>> 1;
    }
    result[i] = count;
  }

  return result;
}

Time: O(n log n) - about O(log i) work for each of the n numbers · Space: O(n), for the output list

Optimal - Build Each Answer From a Smaller One

The bit count of i equals the count for i >> 1 (i without its last bit, already computed) plus 1 if the dropped bit (i & 1) was 1.

function countBits(n) {
  const result = new Array(n + 1).fill(0);

  for (let i = 1; i <= n; i++) {
    result[i] = result[i >> 1] + (i & 1);
  }

  return result;
}

Time: O(n) · Space: O(n), for the output list