sagelearnai

Counting Bits

Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #338

For every integer i from 0 to n, return how many 1 bits it has, as an array of length n + 1. Aim for O(n) overall.

Examples

text
n = 2  →  [0, 1, 1]
n = 5  →  [0, 1, 1, 2, 1, 2]

Hints

  1. Shifting i right by one drops its last bit. How does bits[i] relate to bits[i >> 1]?
  2. This is a tiny DP over integers.

Approach

i >> 1 is i without its lowest bit, so bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 < i, it's already computed. Alternatively, bits[i] = bits[i & (i − 1)] + 1.

Complexity

Time: O(n). Space: O(n) for the output.

Python solution
def countBits(n):
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)
    return bits
JavaScript solution
function 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;
}