150NeetCode 150

146.Counting Bits

EasyBlind 75Bit Manipulation · 3/7

Problem

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

Follow-up: can you do it in O(n) time in a single pass, without a built-in popcount?

Examples

Input:  n = 2
Output: [0, 1, 1]
Explanation:
0 → 0    (0 ones)
1 → 1    (1 one)
2 → 10   (1 one)
Input:  n = 5
Output: [0, 1, 1, 2, 1, 2]
Explanation:
0 → 0, 1 → 1, 2 → 10, 3 → 11, 4 → 100, 5 → 101

Constraints

  • 0 <= n <= 10^5

💡 Key Insight

Every number's bit count is closely related to a smaller number we have already solved. Shifting i right by one drops its last bit, so bits(i) = bits(i >> 1) + (i & 1). Since i >> 1 < i, filling the array from left to right turns this into a simple DP with O(1) work per entry.

Brute Force (Count Each Number)

TimeO(n log n)SpaceO(1) extra (the output array is required).

Intuition

Solve Number of 1 Bits independently for each i from 0 to n, using Kernighan's x & (x - 1) trick to clear one set bit at a time.

Algorithm

  1. Create ans of size n + 1.
  2. For each i, copy x = i; while x != 0, do x &= x - 1 and increment ans[i].
  3. Return ans.

Visualization

i = 5 (101): 101 → 100 → 000   → 2 ones
i = 4 (100): 100 → 000         → 1 one
i = 3 (011): 011 → 010 → 000   → 2 ones

Code

java
class Solution {
    public int[] countBits(int n) {
        int[] ans = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            int x = i;
            while (x != 0) {
                x &= x - 1; // drop lowest set bit
                ans[i]++;
            }
        }
        return ans;
    }
}

Complexity

  • Time: O(n log n) — each number has at most log2(n) + 1 set bits.
  • Space: O(1) extra (the output array is required).

Complexity Comparison

Approach Time Space
Count Each Number O(n log n) O(1)
DP with MSB Offset O(n) O(1)
DP with Right Shift O(n) O(1)

Common Pitfalls

  • Allocating an array of size n instead of n + 1 — the answer must include i = n.
  • Writing ans[i >> 1] + i & 1 without parentheses — + binds tighter than &, so it computes (ans[i >> 1] + i) & 1.
  • In the offset approach, updating offset after using it — at i = 4 you must switch to offset = 4 first, otherwise ans[4] = 1 + ans[2] = 2 (wrong).
  • Forgetting n = 0 — the result is simply [0]; all three solutions handle it because the loop never runs.