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

Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit.

Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit.
def max_xor(a):
    ans = mask = 0
    for b in range(5, -1, -1):
        mask |= 1 << b
        prefixes = {x & mask for x in a}
        cand = ans | (1 << b)
        if any(cand ^ p in prefixes for p in prefixes): ans = cand
    return ans
print(max_xor([3, 10, 5, 25, 2, 8]))
What is printed?
  1. A. 31
  2. B. 27
  3. C. 25
  4. D. 28

Correct answer: D. 28

Build the answer from the top bit: try setting the next bit and check, using the property a ^ b = c ⟺ a ^ c = b, whether two prefixes achieve it. 5 ^ 25 = 00101 ^ 11001 = 11100 = 28. The same idea with a binary trie is O(n · bits).

More Coding Interview Problems questions

Exams that ask this topic