← Back to Algorithms, page 5

algorithms-0096 · Easy fresher

Counting bits: return an array with the number of 1 bits in every integer from 0 to n in linear time.

Reuse earlier answers: shifting i right by one drops its lowest bit, so bits[i] = bits[i >> 1] + (i & 1). Another recurrence removes the lowest set bit: bits[i] = bits[i & (i - 1)] + 1. Either fills the array in O(n) time, compared with O(n log n) when each number is counted separately.

Full answer

Problem

Given n, return bits of length n + 1 where bits[i] is the number of 1s in the binary representation of i.

Example: n = 5 gives [0, 1, 1, 2, 1, 2].

Constraints: 0 <= n <= 10^5. Target O(n) time without a built-in popcount.

Brute force

Count bits for each i separately (string conversion, or a loop over bits): O(log i) each, O(n log n) total.

Optimal approach

bits[0] = 0. For i from 1 to n:

  • Shift recurrence: bits[i] = bits[i >> 1] + (i & 1).
  • Or lowest-bit recurrence: bits[i] = bits[i & (i - 1)] + 1.

Both refer only to smaller indices, which are already filled.

Why it works

i >> 1 is i with its lowest bit removed, so its count differs from i's by exactly that bit, i & 1. Similarly, i & (i - 1) is i with its lowest set bit cleared, which has exactly one fewer 1. Both values are smaller than i, so the array can be filled in increasing order.

Complexity

O(n) time and O(n) space for the output.

Code

python
def count_bits(n):
    """Set-bit counts for 0..n. bits[i] = bits[i >> 1] + (i & 1). O(n) time."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)
    return bits


def count_bits_low(n):
    """Alternative recurrence: dropping the lowest set bit gives a smaller number."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i & (i - 1)] + 1
    return bits


def brute(n):
    """O(n log n): count each number separately."""
    return [bin(i).count("1") for i in range(n + 1)]


if __name__ == "__main__":
    assert count_bits(2) == [0, 1, 1]
    assert count_bits(5) == [0, 1, 1, 2, 1, 2]
    assert count_bits(0) == [0]
    for n in (1, 7, 64, 1000, 4097):
        assert count_bits(n) == count_bits_low(n) == brute(n)
    print("all tests passed")

Save as b96_counting_bits.py and run python3 b96_counting_bits.py. It prints all tests passed (Python 3.13.5).

Edge cases

n = 0 returns [0]. Powers of two have count 1. Values just below a power of two (all ones) have the largest counts.

Pattern

DP over integers using bit relations: the answer for i comes from a smaller number obtained by a bit operation. The same idea powers subset-sum-over-masks DP, Gray code generation, and counting set bits over a range by bit position.

python
def count_bits(n):
    """Set-bit counts for 0..n. bits[i] = bits[i >> 1] + (i & 1). O(n) time."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)
    return bits


def count_bits_low(n):
    """Alternative recurrence: dropping the lowest set bit gives a smaller number."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i & (i - 1)] + 1
    return bits


def brute(n):
    """O(n log n): count each number separately."""
    return [bin(i).count("1") for i in range(n + 1)]


if __name__ == "__main__":
    assert count_bits(2) == [0, 1, 1]
    assert count_bits(5) == [0, 1, 1, 2, 1, 2]
    assert count_bits(0) == [0]
    for n in (1, 7, 64, 1000, 4097):
        assert count_bits(n) == count_bits_low(n) == brute(n)
    print("all tests passed")

Two O(n) recurrences checked against bin(i).count('1') for several n.

Complexity

Time: O(n). Space: O(n) output. The brute force is O(n log n).

By level

Fresher: Writes the shift recurrence and explains it with small binary numbers. Returns an array of length n + 1.

Mid: Gives both recurrences with explanations and computes total set bits from 1 to n by bit position in O(log n). Discusses built-in popcount availability.

Senior: Relates bit-based DP to subset DP and hardware popcount support, and discusses vectorized popcount for large bitsets. Chooses between table lookups and instructions for performance-critical code.

Key points

  • bits[i] = bits[i >> 1] + (i & 1)
  • bits[i] = bits[i & (i - 1)] + 1
  • Both use smaller indices
  • O(n) total
  • bits[0] = 0

Common mistakes

  • Off-by-one array length (needs n + 1)
  • Using a per-number loop and missing the O(n) target
  • Using built-in popcount when the interviewer asked not to
  • Wrong base case

Follow-ups

  • How do you count total set bits from 1 to n without listing them?
  • How would you generate a Gray code sequence?
  • What changes for 64-bit ranges?

Tips

  • Explain the shift relation with a 3-bit example
  • Mention the second recurrence
  • Return n + 1 values

Evaluation rubric

  • Correct recurrence
  • O(n)
  • Correct base case
  • Explains why it works