Counting Bits
Given a non-negative integer n Return an array where ans[i] is the count of 1's in binary of i Example: n = 2 => [0,1,1] (0='0', 1='1', 2='10') Example: n = 5 => [0,1,1,2,1,2]
Counting Bits is about turning repeated work into a reusable state instead of re-solving subproblems. It's a great warm-up that builds state-and-transition thinking without a ton of moving parts. The trap is picking a state that's too vague; keep it minimal and consistent.
Examples
You write
count_bits(n: int)
Example 1
- Input
- n = 2
- returns
- [0,1,1]
Example 2
- Input
- n = 5
- returns
- [0,1,1,2,1,2]
The pattern behind it
Dynamic Programming
I reach for it when
- Brute force repeats the same subproblem.
- You are asked for a count, a minimum or a maximum.
Say this before you type. Say the state in one sentence, then say which smaller states it reads from.
All 37 Dynamic Programming problemsBit Manipulation
I reach for it when
- The statement bans extra space or restricts operators.
- Numbers act as flags, masks or XOR pairs.
Say this before you type. Say what each bit means in this problem before you shift or mask anything.
All 12 Bit Manipulation problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.