Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Bit Manipulation

Counting Bits

EASY✓ CHIP-TIMEDLC #338 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: For every integer from 0 up to n, report how many of its bits are 1 — one array of answers, and the trick is reusing work you already did.

A single non-negative integer n arrives, and the task is to hand back an array covering every integer from 0 through n in order, one entry per value.

Each entry at index i must equal the count of 1-bits in the binary form of i — position 0 always reports zero, since zero has no set bits of its own.

The array's length is fixed at n + 1, and the order always matches the value being described, so index i is the popcount of i itself, never of some other number.

  • n is a single non-negative integer, and can be zero
  • the output array always has exactly n + 1 entries, ordered by index
  • every entry is a non-negative bit count, never negative
  • n can run from tiny up to a value in the hundreds of thousands
EX 01
n = 0
→ [0]
minimum size, just zero
EX 02
n = 1
→ [0, 1]
zero and one
EX 03
n = 2
→ [0, 1, 1]
two is a single bit again

The hintstake only what you need

HINT 1 THE NUDGE

Popcount-ing each number from scratch works but repeats effort — the answer for i is hiding inside the answer for a smaller number you already computed.

HINT 2 THE STRUCTURE

Drop the lowest bit of i by shifting right one place, and you land on a number you've already scored. What did that shift throw away?

HINT 3 ONE STEP FROM THE ANSWER

dp[i] = dp[i >> 1] + (i & 1) — the popcount of i's smaller half plus whichever bit the shift discarded. Build the table left to right.

Coach's boardthe pattern, step by step

THE TABLE OF ONESPATTERN · BUILD ON i >> 1n = 5
0
STEP 1

dp[0] is always 0 — zero has no set bits. Every later index reuses an answer already sitting earlier in the table.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/counting-bits.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def countBits(self, n: int) -> List[int]:
        dp = [0] * (n + 1)
        for i in range(1, n + 1):
            dp[i] = dp[i >> 1] + (i & 1)
        return dp
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 6 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED