Counting Bits – Solution & Complexity

Solution Walkthrough

1. Brute-force baseline

  • For each number i, repeatedly inspect or remove bits until the number becomes zero.
  • That works, but it repeats nearly the same work for neighboring numbers.

2. Reuse smaller answers

  • Shifting i right by one bit removes only the last bit.
  • So the answer for i is the answer for i >> 1 plus the removed bit.

3. Fill the DP from left to right

  • Once answer[0] is known, every later value depends only on an earlier index.
  • That makes a simple forward loop enough.

4. Final solution (all languages)

Dynamic programming over the previous half-value gives every popcount in linear time.

def counting_bits(n: int) -> list[int]:
    answer = [0] * (n + 1)
    for i in range(1, n + 1):
        answer[i] = answer[i >> 1] + (i & 1)
    return answer

5. Complexity summary

  • Time: O(n).
  • Space: O(n) for the returned array.

FAQ