Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count set bits for each number 0..n using DP on the lowest bit.

Problem: Count set bits for each number 0..n using DP on the lowest bit.
def bits(n):
    r = [0] * (n + 1)
    for i in range(1, n + 1):
        r[i] = r[i >> 1] + (i & 1)
    return r
print(bits(10))
What is printed?
  1. A. [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 3]
  2. B. [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4]
  3. C. [0, 1, 1, 2, 2, 2, 2, 3, 1, 2, 2]
  4. D. [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]

Correct answer: D. [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]

i has the same bits as i >> 1 plus its lowest bit. 7 = 111 → 3, 8 = 1000 → 1, 10 = 1010 → 2. O(n) total, versus O(n log n) counting each number separately. (The third option is ⌊log₂ i⌋ + 1, the bit length.)

More Coding Interview Problems questions

Exams that ask this topic