Counting Bits

EasyBit Manipulation · DP🧩 Bit ManipulationLeetCode #338 ↗Updated

Problem

Given a non-negative 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, for every 0 ≤ i ≤ n.
Inputn = 2Output[0,1,1]
Inputn = 5Output[0,1,1,2,1,2]

0 ≤ n ≤ 105  ·  Follow-up: O(n) in a single pass, without built-ins like Integer.bitCount.

Try it yourself

Java
class Solution {
    public int[] countBits(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Every number is a smaller number plus one bit: i equals i >> 1 with its last bit (i & 1) appended. So ans[i] = ans[i >> 1] + (i & 1) reuses an answer already computed.
PatternBit Manipulation

Instinct Pairs that cancel, counting 1s, powers of two, subsets as numbers, or 'no + or - allowed' - drop to binary and use XOR, AND, OR and shifts.

Memory hack XOR is a forgetful twin detector - see something twice and it vanishes; n & (n-1) snips off the last lit bulb.

Open the Bit Manipulation guide →

Approaches

Brute ForceCount Each Number Bit by Bit

Time O(n log n)Space O(1) extra

For each i, peel off bits with % 2 and / 2 until it reaches 0. A number has about log2i bits, so the total work is O(n log n). (The output array itself is O(n) and not counted.)

Java
public int[] countBits(int n) {
    int[] res = new int[n + 1];
    for (int i = 0; i <= n; i++) {
        int count = 0, num = i;
        while (num > 0) {
            count += num % 2; // lowest bit
            num /= 2;         // drop it
        }
        res[i] = count;
    }
    return res;
}

Obvious and correct, but recomputes overlapping work for every number.

At a glance

LevelApproachTimeSpace
Brute ForceCount Each Number Bit by BitO(n log n)O(1) extra
BetterDP on Highest Power of TwoO(n)O(1) extra
OptimalDP on Last Bit (i >> 1)O(n)O(1) extra
Common pitfalls
  • Allocating n instead of n + 1 slots — misses ans[n].
  • Operator precedence: res[i >> 1] + i & 1 parses as (res[..] + i) & 1.
  • Starting the DP loop at 0 without the base case res[0] = 0 in mind.
Interview tips
  • Start with per-number counting, then spot that i and i/2 share bits.
  • Name it as DP: subproblem i >> 1 is always solved earlier.
  • Mention i & (i-1) (Kernighan) — it reappears in Number of 1 Bits and Power of Two.
Pattern
Bit DP → when a value's answer for i follows from a smaller related value (i>>1, i&(i-1)).
My notes saved in this browser