Counting Bits

Easy

Topics
Dynamic ProgrammingBit Manipulation

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.

Example 1

2100 → 00001 → 10012 → 1010
Each row is one number with its set-bit count.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 2
Output: [0,1,1]

Example 2

2100 → 00001 → 10012 → 10103 → 20114 → 11005 → 2101
Input:  n = 5
Output: [0,1,1,2,1,2]

Constraints

  • 0 <= n <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every number i is some smaller number i >> 1 with one extra bit shifted in. So bits(i) = bits(i/2) + (i & 1) — the low bit tells you whether the shift dropped a 1.

Approach

  1. Allocate ans of size n+1 with ans[0]=0.
  2. For each i from 1 to n set ans[i] = ans[i >> 1] + (i & 1).

Dry Run

n = 8
ans[i] = ans[i >> 1] + (i & 1)  --  i with its low bit shifted off, plus that bit
  i=1     1   i>>1=0     0   ans[0]=0  + 1  ->  ans[1]=1
  i=2    10   i>>1=1     1   ans[1]=1  + 0  ->  ans[2]=1
  i=3    11   i>>1=1     1   ans[1]=1  + 1  ->  ans[3]=2
  i=4   100   i>>1=2    10   ans[2]=1  + 0  ->  ans[4]=1
  i=5   101   i>>1=2    10   ans[2]=1  + 1  ->  ans[5]=2
  i=6   110   i>>1=3    11   ans[3]=2  + 0  ->  ans[6]=2
  i=7   111   i>>1=3    11   ans[3]=2  + 1  ->  ans[7]=3
  i=8  1000   i>>1=4   100   ans[4]=1  + 0  ->  ans[8]=1
answer 0 1 1 2 1 2 2 3 1
Read the binary column and the recurrence stops being clever: i >> 1 is literally i
with its last digit rubbed out, so the only open question is whether that digit was
a 1, and i & 1 answers it. The powers of two reset to 1 (see i=4 and i=8) because
everything below the top bit is zero.
The pass can run forward with no recursion and no memo dictionary for one reason:
i >> 1 < i for every i >= 1, so the cell being read was filled on an earlier
iteration. That is also why ans[0] = 0 has to be seeded -- i=1 reads it.

Complexity

  • Time — O(n): one pass filling the table, each entry O(1).
  • Space — O(n): the output array (aside from output, O(1)).

Common Pitfalls

  • ans[i >> 1] counts the bits of i with its lowest bit shifted off, so the lowest bit has to be added back with i & 1. Dropping that term returns all zeros, because every value traces back to ans[0].
  • The recurrence only works because i >> 1 < i for every i >= 1, so the entry it reads is always already filled.

Full Solution — all languages

class Solution:
    def countBits(self, n):
        ans=[0]*(n+1)
        for i in range(1,n+1):
            ans[i]=ans[i>>1]+(i&1)
        return ans
Asked at Qualcomm
SensAI
Beta
Tap the mic to stop voice mode