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?
  1. A. 12 4 8 0
  2. B. 15 4 0 1
  3. C. 12 4 0 0
  4. 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

Exams that ask this topic