Skip to content
AI360Xpert
Beta
Difficulty: EasyBit Manipulation

Counting Bits

Problem in Plain English

Build an array where entry i holds the number of 1 bits in the binary form of i, for every i from 0 up to n.

Problem Statement

Given an integer n, return an array ans of length n + 1 where ans[i] counts the number of 1 bits in the binary form of i, for every i from 0 to n.

Counting each number from scratch repeats work, because smaller answers already reveal larger ones: stripping the lowest set bit, or halving the number, lands on a value already computed. Aim for one linear pass with no built-in bit counter.

Constraints

  • 0≤n≤1050 \le n \le 10^5

Examples

Example 1

Input
n = 2
Output
[0, 1, 1]

0 has zero ones, 1 has one, and 2 (10 in binary) has one.

Example 2

Input
n = 5
Output
[0, 1, 1, 2, 1, 2]

3 (11) has two ones, 4 (100) has one, and 5 (101) has two.

Example 3

Input
n = 0
Output
[0]

The range still includes zero. Its binary representation has no set bits, so the returned array has one entry rather than being empty.

Intuition

Binary digits describe how many powers of two make a number; count only the digits equal to one. Example 1 needs answers for 0, 1 and 2: their binary forms 0, 1 and 10 contain 0, 1 and 1 ones. Counting each separately works, but removing the last digit of 2 leaves 1, whose answer is already available. The removed digit contributes either zero or one, so smaller answers can build the entire array.

Approaches

Count Each Number

Solution Details

Reveal Count Each Number: intuition, complexity, and code

Hints

Hint 1
Compare neighbors: 4 (100) has the same count as 2 (10), and 5 (101) has one more. What operation turns one into the other?
Hint 2
Shifting right by one halves the number and drops its last bit; that bit equals i & 1.
Hint 3
Fill dp[i] = dp[i >> 1] + (i & 1) left to right from dp[0] = 0, since the halved index is always already computed.

Edge Cases

  • n = 0 returns [0]. The DP loop never runs; the baseline evaluates zero without clearing any bit.
  • Powers of two such as 8 (binary 1000) have exactly one set bit. The recurrence follows dp[8] = dp[4] = dp[2] = dp[1] = 1, with dp[1] = dp[0] + 1.
  • The maximum n = 100000 still fills in one pass with no per-number inner loop.

Common Mistakes and Interview Tips

  • Recounting every number is a valid baseline, but does not meet the linear-time follow-up; explain how the DP recurrence avoids that repeated work.
  • Writing dp[i >> 1] + i & 1 without parentheses where the language parses it as (dp[i >> 1] + i) & 1.
  • Sizing the answer as length n instead of n + 1, dropping the entry for n itself.

Key Takeaway

When answers for 0 to n build on each other, look for a one-step reduction — here halving — that turns earlier results into current ones.