Data Structures & AlgorithmsHardProduct company OA
Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros.
Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros.
def and_range(m, n):
shift = 0
while m < n: m >>= 1; n >>= 1; shift += 1
return m << shift
print(and_range(12, 15), and_range(5, 7), and_range(8, 16), and_range(1, 1 << 20))What is printed?- A. 12 4 8 0
- B. 15 4 0 1
- C. 12 4 0 0
- D. 12 5 0 0
Correct answer: C. 12 4 0 0
Any bit below the first position where m and n differ takes both values somewhere in the range, so it ANDs to 0. 12 = 1100, 15 = 1111 → common prefix 11 → 1100 = 12. 5 = 101, 7 = 111 → 100 = 4. 8 = 01000 and 16 = 10000 share no prefix → 0. Looping over all numbers is O(n − m), far too slow for ranges up to 2³¹.
More Coding Interview Problems questions
- 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…
- 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]…