InterviewPrepKit

Home / Coding / Bit Manipulation

Counting Bits

easy Original β†—
Solving tips
  • Reuse an already-solved smaller number instead of counting each value from scratch: this is a DP with an O(1) recurrence per entry.
  • Recurrence A: ans[i] = ans[i >> 1] + (i & 1), dropping the lowest positional bit; Recurrence B: ans[i] = ans[i & (i-1)] + 1, clearing the lowest SET bit.
  • Both build the table left to right in O(n) total time, O(1) extra space beyond the length-(n+1) output array.
  • Pitfalls: output has n+1 entries, and keep parentheses in ans[i>>1] + (i & 1) since & binds looser than +.

Problem

Given an integer n, return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary representation of i, for every i from 0 to n inclusive.

Examples

  • n = 2 β†’ [0, 1, 1] β€” 0 is 0, 1 is 1, 2 is 10.
  • n = 5 β†’ [0, 1, 1, 2, 1, 2] β€” 3 is 11 (two bits), 5 is 101 (two bits).
  • n = 0 β†’ [0] β€” only zero, which has no set bits.

Constraints

  • 0 <= n <= 10^5

The easy answer counts each number independently. The follow-up asks for a single O(n) pass that does not call a built-in popcount and does no per-number bit loop.

Think about it first

Hint 1 Counting each number from scratch repeats work. Every `i` is closely related to a smaller number you have *already* solved β€” can you reuse that answer?
Hint 2 `i >> 1` is `i` with its lowest bit chopped off, and `i & 1` is exactly that lowest bit. So `popcount(i) = popcount(i >> 1) + (i & 1)`.
Hint 3 Alternatively, `i & (i - 1)` erases the lowest *set* bit, giving a smaller number that has exactly one fewer `1`. So `ans[i] = ans[i & (i - 1)] + 1`. Either recurrence fills the array left to right in O(1) per entry.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.