Python coding

Largest XOR of two numbers

Given a list nums of non-negative integers, return the largest value of nums[i] ^ nums[j] (bitwise XOR) over all pairs of positions. Using the same position twice is allowed and gives 0, so a single number returns 0.

Numbers are below 2³¹ and the list has at least one. Aim for O(n · bits), not a check of every pair.

  • max_xor([5,1,12,9]) → 13
  • max_xor([7]) → 0
  • max_xor([3,8,15,6,10]) → 14
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

XOR is largest when the highest bits differ. Store every number's bits, highest first, in a trie whose nodes have two children: one for 0 and one for 1.

Hint 2

For a number x, walk down from the root and take the child with the opposite bit whenever it exists: that bit becomes 1 in the XOR. Otherwise follow the same bit.

Hint 3

The greedy is safe because one higher bit outweighs all the lower bits together. Give every number the same width, max(nums).bit_length() bits, so the levels line up.

Solution and why it works
pythonO(n·B), B = bits of the largest number · O(n·B) for the trie
def max_xor(nums: list[int]) -> int:
    bits = max(nums).bit_length()
    root, best = [None, None], 0              # node = [child for bit 0, child for bit 1]
    for x in nums:
        node = root
        for b in range(bits - 1, -1, -1):     # insert x, highest bit first
            bit = (x >> b) & 1
            if node[bit] is None:
                node[bit] = [None, None]
            node = node[bit]
        node, mine = root, 0
        for b in range(bits - 1, -1, -1):     # greedy: step to the opposite bit when it exists
            want = 1 - ((x >> b) & 1)
            if node[want] is not None:
                mine |= 1 << b
                node = node[want]
            else:
                node = node[1 - want]
        best = max(best, mine)
    return best

XOR rewards differing bits, and one higher bit is worth more than all the lower bits together, so the best partner for x can be chosen greedily from the top bit down. A binary trie of the numbers turns that greedy into a walk: at each level take the opposite-bit child if it exists. That costs O(bits) per number instead of trying every pair, O(n²). Trap: every number must use the same bit width, or the trie levels of short and long numbers don't line up.