TRIE-P5

The largest XOR of two numbers

Practice 5 of 5Tries9 tests

The problem

Return the largest value of nums[i] ^ nums[j] for two different positions i and j. ^ is XOR: a result bit is 1 where the two numbers’ bits differ.

max_xor([3, 10, 5, 25, 2, 8])   # 28, from 5 ^ 25
max_xor([1, 2])                 # 3
max_xor([7, 7, 7])              # 0

In binary, 5 is 00101 and 25 is 11001, so 5 ^ 25 is 11100, which is 16 + 8 + 4 = 28.

Limits

  • 2 to 20,000 numbers, each from 0 to 230 − 1 (at most 30 bits). Comparing every pair is too slow; aim for O(n · B) with B bits.

Builds on TRIE-5 Bitwise tries for XOR.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1Six numbersNot run
2The lesson's numbersNot run
3Two numbersNot run
4All the sameNot run
5ZerosNot run
6Large valuesNot run
7Powers of twoNot run
8The opposite bit is missingNot run
920,000 numbersNot run