LeetCode ยท #338

Counting Bits Solution

Return an array where ans[i] is the number of 1 bits in the binary representation of i, for 0 โ‰ค i โ‰ค n.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #338

๐Ÿ—๏ธ

Pattern

DP + Bits

Example
Input: n = 5 Output: [0,1,1,2,1,2] // 0โ†’0, 1โ†’1, 10โ†’1, 11โ†’2, 100โ†’1, 101โ†’2
02
Section Two ยท Approach 1

Count Each โ€” O(n log n)

For each number 0..n, count its bits using Brian Kernighan's trick. O(log n) per number.

Better: Use DP: dp[i] = dp[i >> 1] + (i & 1). The bit count of i is the bit count of i/2 plus whether the last bit is set. O(1) per number, O(n) total.
03
Section Three ยท Approach 2

DP โ€” O(n) time, O(1) extra

dp[i] = dp[i >> 1] + (i & 1). Right-shifting i removes the last bit โ€” we already know the bit count of the shifted value. Add 1 if the removed bit was 1.

๐Ÿ’ก Mental model: "How many 1s in 13 (1101)?" = "How many 1s in 6 (110)?" + "Is the last bit 1?". 6 has 2 ones, last bit is 1 โ†’ 3.
Alternative DP: dp[i] = dp[i & (i-1)] + 1. Uses Brian Kernighan's trick: i & (i-1) removes the lowest set bit. The bit count increases by exactly 1.
04
Section Four ยท Trace

Visual Walkthrough

Counting Bits โ€” DP
dp[i] = dp[i>>1] + (i&1) i: 0 1 2 3 4 5 dp: 0 dp[0]+1=1 dp[1]+0=1 dp[1]+1=2 dp[2]+0=1 dp[2]+1=2 Result: [0, 1, 1, 2, 1, 2] โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” DP
class Solution { public int[] countBits(int n) { int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) dp[i] = dp[i >> 1] + (i & 1); return dp; } }
Python โ€” DP
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
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
Count eachO(n log n)O(n)
DP โ† optimalO(n)O(n) output
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
n=00Return [0].
n=11Return [0,1].
Power of 2n=8dp[8]=dp[4]+0=1. Single bit.
โš  Common Mistake: Off-by-one: array should be size n+1 (indices 0 to n inclusive).

โ† Back to Math & Bit problems