LeetCode 338 Counting Bits - Why Naive Fails

The trap

For each number, count its bits individually using Brian Kernighan's trick.

Each count takes O(k)O(k) where kk is the number of set bits. Summed over nn numbers, that's O(nlogn)O(n \log n) in the worst case.

Can you compute each count in O(1)O(1) using previous results?