#421

Maximum XOR of Two Numbers in an Array

Medium Binary trie

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

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

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the biggest XOR of any two numbers.

Why this works: store numbers bit by bit from the top. For each number, try to go the opposite way at every bit; a 1 in a high bit beats anything lower.

Example: [3, 10, 5, 25, 2, 8]

5 (00101) with 25 (11001) → 11100 = 28

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Walking from the lowest bit up — the highest bits matter most, so go from the top.

Solve on LeetCode ↗
Complexity
  • Time: O(n · 31).
  • Space: O(n · 31).
Topic: Trie
🎬 Episode 97: video coming soon