SDE & MLE Prep

421. Maximum XOR of Two Numbers in an Array

Problem

Return the maximum of nums[i] XOR nums[j] over all pairs i ≤ j.

Example: [3,10,5,25,2,8] → 28 (5 XOR 25)

Constraints: n ≤ 2·10⁵; values < 2³¹.

Insert numbers as 31-bit binary strings into a trie (high bit first). For each number, walk greedily toward the opposite bit at every level to maximize XOR.

x = 5 = 00101   want bits 11010 -> follow opposite branches when they exist
best partner for 5 in [3,10,5,25,2,8] is 25 (11001) -> 5^25 = 28

Complexity: O(32 · n).

class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        root, best = {}, 0
        for x in nums:
            node = root
            for b in range(30, -1, -1):
                node = node.setdefault((x >> b) & 1, {})
        for x in nums:
            node, cur = root, 0
            for b in range(30, -1, -1):
                bit = (x >> b) & 1
                if 1 - bit in node:
                    cur |= 1 << b
                    node = node[1 - bit]
                else:
                    node = node[bit]
            best = max(best, cur)
        return best