Given an integer n, return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i.
Before you code
Counting the bits of every number separately takes about 32 steps per number. You can do it in one step per number by noticing that each number's bits are another, smaller number's bits plus at most one more.
Hints
i >> 1isiwith its lowest bit removed, and it is smaller thani, so its answer is already in the array.- So
ans[i] = ans[i >> 1] + (i & 1). - Check it on 5 (101):
ans[2]is 1, and the lowest bit of 5 is 1, soans[5]is 2.
Production & complexity notes
When solving Counting bits on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Bits, bytes and number representation to reinforce the underlying pattern.
What it practices
Shifting and masking bits, from Bits, bytes and number representation. Reusing an earlier answer is also the core idea of dynamic programming, later in the track.