Problem 421 · LeetCode 421(opens in a new tab)
Maximum XOR of Two Numbers in an Array
MediumBit manipulation
You get a list of non-negative integers, nums. Pick two of them, possibly the same position twice, and combine them with bitwise XOR (a bit of the result is 1 when the two bits differ).
Return the largest XOR you can get from any such pair.
Example 1
Input: nums = [3, 5, 6, 1] Output: 7 Why: 6 XOR 1 = 110 XOR 001 = 111 = 7
2 more examples and the constraints
Example 2
Input: nums = [9] Output: 0 Why: the only pair is 9 with itself
Example 3
Input: nums = [8, 10, 2] Output: 10 Why: 8 XOR 2 = 1000 XOR 0010 = 1010
Constraints
- 1 ≤ length of nums ≤ 200,000
- 0 ≤ nums[i] ≤ 2³¹ − 1
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- Bitwise trie, greedyO(31·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200,000 numbers | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Too slow at the limit | |
| Bitwise trie, greedy | O(31·n) | Best; linear in n |
n = length of nums; 31 = bits per number.
Edge cases to test
- One number. [9] gives 0: the only pair is the number with itself.
- All the same. [4, 4, 4] gives 0.
- Zero and the largest value. [0, 2147483647] gives 2147483647; every bit differs.
- Powers of two. [1, 2, 4, 8, 16] gives 24, from 8 XOR 16.
Common mistakes
- Walking the bits from low to high; only a high-to-low walk lets the greedy choice be safe.
- Using fewer than 31 bits, which drops the top bits of large values.
- Querying a number before any number is in the trie and then reading a missing child.
How to talk through it
- 1Clarify. Can I pair a number with itself? Are values non-negative? How many bits can they have?
- 2Give the brute force. XOR every pair: O(n²), about 20 billion pairs at the limit.
- 3Use the bit weights. One high bit beats all lower bits together, so decide the answer bit by bit from the top.
- 4Build the trie. Store bits high to low; for each x, walk taking the opposite bit when it exists.
- 5Test out loud. Run one number, equal numbers, and 0 with the largest value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?