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?- A. [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 3]
- B. [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4]
- C. [0, 1, 1, 2, 2, 2, 2, 3, 1, 2, 2]
- 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
- Problem: Check whether a number is a power of two and isolate its lowest set bit. python print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x…
- Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space. python def single(a): ones = twos…
- Problem: Two values appear once and every other value twice. Find both (smaller first). python def twosingle(a): x = 0 for v in a: x ^= v…
- Problem: Count the bits that differ between two IDs (Hamming distance) and the total over all pairs of an array. python def ham(x, y)…
- Problem: A permissions mask is an int; report how many permissions (set bits) each mask grants. java static int popc(int x) { return…
- Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum. python a = [3, 4, 5, 6] cnt = 0 for…