InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Counting Bits

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug