Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros then 2^b ones.
Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros then 2^b ones.
def total_bits(n):
total, b = 0, 0
while (1 << b) <= n:
cycle = 1 << (b + 1)
total += (n + 1) // cycle * (1 << b) + max(0, (n + 1) % cycle - (1 << b))
b += 1
return total
print(total_bits(5), total_bits(16), total_bits(1000))What is printed?- A. 7 32 4938
- B. 7 33 4938
- C. 7 33 5000
- D. 8 33 4938
Correct answer: B. 7 33 4938
For bit b, the numbers 0..n contain (n + 1) // 2^(b+1) full cycles, each with 2^b ones, plus a partial cycle that contributes max(0, remainder − 2^b). 0..5: 0, 1, 1, 2, 1, 2 → 7. 0..16: 32 ones in 0..15 plus 1 for 16 → 33. 0..1000 → 4938 (a brute-force popcount sum agrees). O(log n).
More Coding Interview Problems questions
- Problem: Minimum single-bit flips in a and b so that (a OR b) == c. python def minflips(a, b, c): flips = 0 while a or b or c: x, y, z = a…
- Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by…
- Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word. python…
- Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and…
- Problem: Count triples (i, j, k) with i < j ≤ k such that XOR(a[i..j−1]) == XOR(a[j..k]). This holds iff XOR(a[i..k]) = 0, i.e. prefix[i]…
- Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder…