Skip to main content
72

Counting Bits

Easybit manipulationdynamic programming

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Bit ManipulationRead the beginner guide

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.

Understand the problem

  • For each number from 0 to n, write it in binary and count its 1s.
  • Return all the counts in one array, in order.
  • If you haven't solved Number of 1 Bits yet, it's the one-number version of this problem.

Example 1

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

0 is 0, 1 is 1, 2 is 10.

Example 2

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

0, 1, 10, 11, 100, 101.

Example 3

text
Input:  n = 0
Output: [0]

Constraints

  • 0 <= n <= 10^5

Tip

Calling Number of 1 Bits for each i is O(n log n). Can you do it in O(n), in a single pass?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Every number is a smaller number (itself shifted right by one) plus one more bit at the bottom, so its count is that smaller number's count, already computed, plus that last bit.

    The naive approach (and why it's slower)

    Count the bits of each number from scratch, as in Number of 1 Bits. A number up to n has about log n bits, so this is O(n log n). It's acceptable, but we can avoid redoing work.

    The key insight: DP on bits

    This is dynamic programming: the answer for i is built from the answer for a smaller number that's already in the array.

    i >> 1 shifts i right by one: it drops the lowest bit (the same as Math.floor(i / 2)). So i's bits are exactly i >> 1's bits, plus the dropped bit, which is i & 1:

    text
    bits[i] = bits[i >> 1] + (i & 1)
    text
    5     = 101
    5 >> 1 = 10   (that's 2, with 1 one)
    5 & 1  = 1    (the dropped bit)
    bits[5] = bits[2] + 1 = 2

    Since i >> 1 < i for every i >= 1, filling the array from 1 upward always finds the smaller answer ready. The base case is bits[0] = 0.

    Step by step

    n = 5:

    iBinaryi >> 1bits[i >> 1]i & 1bits[i]
    000
    110011
    2101101
    3111112
    41002101
    51012112

    Answer: [0, 1, 1, 2, 1, 2].

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). One O(1) step per number.
    • Memory: O(1) besides the output array.

    Common mistakes

    • Forgetting bits[0] = 0, or starting the loop at 0 and reading bits[0] before it's set.
    • Mixing up i >> 1 and i << 1. Shifting left makes the number bigger, and that answer isn't known yet.
    • An array of length n instead of n + 1: the range includes n itself.

    Going deeper

    Another formula works too: bits[i] = bits[i & (i - 1)] + 1. i & (i - 1) is i with its lowest 1 removed (the trick from Number of 1 Bits), so it has exactly one fewer 1.

    Reference solution

    js
    /**
     * @param {number} n
     * @return {number[]}
     */
    export default function countBits(n) {
      // bits[0] = 0. Every other entry is filled from a smaller index.
      const bits = new Array(n + 1).fill(0)
      // i >> 1 is i without its lowest bit (already computed, since it's smaller);
      // i & 1 is that dropped bit.
      for (let i = 1; i <= n; i++) bits[i] = bits[i >> 1] + (i & 1)
      return bits
    }
    ts
    export default function countBits(n: number): number[] {
      // bits[0] = 0. Every other entry is filled from a smaller index.
      const bits = new Array<number>(n + 1).fill(0)
      // i >> 1 is i without its lowest bit (already computed, since it's smaller);
      // i & 1 is that dropped bit.
      for (let i = 1; i <= n; i++) bits[i] = bits[i >> 1] + (i & 1)
      return bits
    }
    python
    def count_bits(n: int) -> list[int]:
        # bits[0] = 0. Every other entry is filled from a smaller index.
        bits = [0] * (n + 1)
        for i in range(1, n + 1):
            # i >> 1 is i without its lowest bit (already computed, since it's smaller);
            # i & 1 is that dropped bit.
            bits[i] = bits[i >> 1] + (i & 1)
        return bits