SDE & MLE Prep

338. Counting Bits

Problem

For every i from 0 to n, count the 1 bits in i's binary form, and return the counts as a list.

Example: n = 5 → [0,1,1,2,1,2]

Constraints: follow-up: O(n) without a built-in popcount.

bits[i] = bits[i >> 1] + (i & 1) — drop the last bit, reuse the answer.

Complexity: O(n).

class Solution:
    def countBits(self, n: int) -> List[int]:
        bits = [0] * (n + 1)
        for i in range(1, n + 1):
            bits[i] = bits[i >> 1] + (i & 1)
        return bits