easyMathDynamic Programming

Counting Bits

easyTime: O(n)Space: O(n)

Signals to notice

count set bits for every number 0 to npattern in binary representationsbuild from smaller results

Brute force first

For each number, count its bits individually. Each number is processed independently, ignoring the relationship between consecutive numbers. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

dp[i] = dp[i >> 1] + (i & 1). Each number's bit count equals its right-shifted version's count plus its last bit. This works because right-shifting removes the last bit, and we already know the answer for the smaller number. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

Every number's bit count can be derived from a smaller number's bit count plus 0 or 1. The recurrence dp[i] = dp[i/2] + (i % 2) captures this — we never need to count bits from scratch. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Not seeing the DP relationship — trying to count bits for each number independently. The key insight is that i >> 1 is always a number we've already computed. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Dynamic Programming Pattern