Counting Bits (LeetCode 338): Solution and Explanation

Easy
Dynamic Programming
Bit Manipulation

For a given n, build an array of length n + 1 where position i holds how many 1 bits appear in the binary form of i. The challenge is to do it faster than counting each number's bits from scratch.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious approach loops over every number from 0 to n and counts its set bits, either by shifting through all bits or with the x & (x - 1) trick. That costs O(n log n) in total, because each number has up to about log n bits. It is acceptable, but the follow up asks for O(n), which means each answer has to come from an earlier answer in constant time.

Look at how binary numbers repeat. The numbers 4 through 7 are written 100, 101, 110 and 111, which are just 0 through 3 (00, 01, 10, 11) with a leading 1 placed in front. In general, every number i between a power of two p and 2p - 1 equals p plus a smaller number i - p, and adding p only sets one extra bit. So the bit count of i is one more than the bit count of i - p.

The reference code tracks that power of two in a variable called offset. It starts at 1, and whenever i reaches offset * 2, i itself is the new power of two, so offset moves up to i. Then dp[i] = 1 + dp[i - offset]. Every answer is built from an earlier entry in the same array, which is dynamic programming in its simplest form.

Other recurrences work too. dp[i] = dp[i >> 1] + (i & 1) drops the lowest bit, and dp[i] = dp[i & (i - 1)] + 1 removes the lowest set bit. They all rely on the same idea of reducing i to a smaller number whose answer is already known.

Approach: DP on the most significant bit

  1. Create dp of length n + 1 filled with zeros; dp[0] stays 0.
  2. Set offset = 1, the largest power of two not above the current i.
  3. Loop i from 1 to n.
  4. If offset * 2 == i, then i is a new power of two, so set offset = i.
  5. Set dp[i] = 1 + dp[i - offset], counting the top bit plus the bits of the remainder.
  6. Return dp.

Step-by-step example

n = 5
  1. dp[0] = 0. For i = 1, offset stays 1, so dp[1] = 1 + dp[0] = 1.
  2. For i = 2, offset * 2 == 2, so offset becomes 2 and dp[2] = 1 + dp[0] = 1.
  3. For i = 3, dp[3] = 1 + dp[1] = 2, since 3 is 11 in binary.
  4. For i = 4, offset becomes 4 and dp[4] = 1 + dp[0] = 1.
  5. For i = 5, dp[5] = 1 + dp[1] = 2. The result is [0, 1, 1, 2, 1, 2].

Code: Python, Java, C++

1class Solution:
2    def countBits(self, n: int) -> List[int]:
3        dp = [0] * (n + 1)
4        offset = 1
5
6        for i in range(1, n + 1):
7            if offset * 2 == i:
8                offset = i
9            dp[i] = 1 + dp[i - offset]
10
11        return dp

Time and space complexity

Time

O(n)

Each of the n + 1 entries is computed with a constant number of operations.

Space

O(1)

Apart from the output array, which is required, only the offset variable is used.

Other approaches

Count bits per number (time O(n log n), space O(1))

For each i, repeatedly clear the lowest set bit with x &= x - 1 and count the iterations. Simple, but each number costs up to log n steps.

Right shift recurrence (time O(n), space O(1))

Use dp[i] = dp[i >> 1] + (i & 1): shifting right drops the last bit, and i & 1 adds it back if it was 1. It needs no offset variable and is the most common one-liner.

Common mistakes

  • Updating offset after computing dp[i] instead of before gives dp[2] = 1 + dp[1] = 2, even though 2 is 10 in binary with a single 1 bit.
  • Starting the loop at 0 makes dp[0] = 1 + dp[-1], which in Python reads the last element.
  • Returning an array of length n instead of n + 1 drops the answer for n itself.
  • Relying on a built-in popcount technically works but ignores the linear time follow up an interviewer is usually asking about.

Frequently asked questions

How do you count bits for every number from 0 to n in O(n)?

Reuse earlier answers. Every number equals a smaller number plus one extra bit, either its highest power of two or its last bit, so each entry is computed from an earlier one in constant time.

What does dp[i] = dp[i >> 1] + (i & 1) mean?

Shifting i right by one removes its lowest bit, giving a smaller number whose count is known. Adding i & 1 puts that removed bit back if it was a 1.

Can you solve Counting Bits without built-in functions?

Yes, all the DP recurrences use only additions, shifts and bitwise AND, which is what the follow up asks for.

What is the space complexity?

The output array of size n + 1 is required, and beyond that the solution uses O(1) extra space.