Skip to content
DSA Patterns
Menu
Language
Bit ManipulationLC #3385 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Counting Bits

Problem (restated)

For each i in 0..n inclusive, return the number of 1-bits in binary representation of i.

Intuition

Right-shift drops LSB; add back (i & 1). Reuses smaller answers → O(n) total.

Approaches

DP: dp[i] = dp[i>>1] + (i&1)

Unverified
Time O(n)Space O(n)

Idea. Equivalent to dp[i] = dp[i & (i-1)] + 1 (popcount recurrence).

Walkthrough. n=5 → [0,1,1,2,1,2].

Trade-offs. Per-number Brian Kernighan is O(n log n) worst.

Solution
export function countBits(n: number): number[] {
  const dp = Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) dp[i] = dp[i >> 1]! + (i & 1);
  return dp;
}
export function countBits(n: number): number[] {
  const dp = Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) dp[i] = dp[i >> 1]! + (i & 1);
  return dp;
}

Template connection

dp[i] = dp[i >> 1] + (i & 1). The shift reuses the popcount of i without its lowest bit, and i & 1 adds that bit.

Reflection

  • dp[i] = dp[i >> 1] + (i & 1). The shift drops one bit. Add 1 when that bit was set.
  • dp[0] = 0. n = 0 answers [0]. n = 1 answers [0, 1].
  • Each i reads a smaller index. The loop runs from 1 through n.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Popcount table for every i in 0..5. dp[i] = dp[i>>1] + (i&1).

0
0
1
1
2
2
3
3
4
4
5
5

dp[0] = 0

Key:MatchSettled