Python 0421.py
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
result = 0
# remove duplicates and sort
nums = set(nums)
# highest actually set bit
high = max(nums)
maxbit = high.bit_length()
# can't get any better than this
optimal = 1 << (maxbit + 1) - 1
# begin with highest bits
mask = 0
most = 2 # at most 2 candidates in first round, then 4, 8, 16, ...
for bit in reversed(range(maxbit)):
current = 1 << bit
mask |= current
limit = result | current
one = set()
for n in nums:
one.add(n & mask)
if len(one) == most: # early exit: all possible bitmasks
break
most <<= 1
for candidate in one:
if limit ^ candidate in one:
result = limit
# early exit: perfect pair found
if result == optimal:
return result
return result
Difficulty
and has an acceptance rate of about 54% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Hash Table
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the maximum XOR value obtainable from any pair of integers in a given list. It first eliminates duplicate values and determines the most significant bit that can influence the result. By iteratively constructing a mask that reveals progressively lower bits, the algorithm narrows down candidate prefixes and checks whether a complementary prefix exists to achieve a higher XOR. Early-exit conditions are used both when the set of prefixes reaches its theoretical maximum for a given bit width and when the optimal XOR value is found.
Key Steps
The algorithm begins by removing duplicate entries from the input and converting the collection to a set for O(1) membership checks.
nums = set(nums)
It then identifies the highest set bit among the remaining numbers, which defines the range of bits that need to be examined.
high = max(nums)
maxbit = high.bit_length()
An upper bound for the XOR result is calculated as a number with all bits set up to one position beyond the most significant bit. This bound represents the theoretical maximum achievable XOR for the given bit width.
optimal = 1 << (maxbit + 1) - 1
The core loop processes bits from the most significant down to the least significant. For each iteration a mask is extended to include the current bit, and a tentative limit is formed by setting that bit in the current result.
mask |= current
limit = result | current
A temporary set one collects the distinct prefixes of the numbers when masked with the current mask. The loop stops early if the number of distinct prefixes reaches the maximum possible count for the current iteration, which is tracked by the variable most.
one = set()
for n in nums:
one.add(n & mask)
if len(one) == most:
break
most <<= 1
After the prefix set is built, the algorithm checks whether any two prefixes can combine to reach the tentative limit. This is done by testing if the XOR of the limit with a candidate prefix exists in the same set. If such a pair is found, the result is updated to the limit.
for candidate in one:
if limit ^ candidate in one:
result = limit
if result == optimal:
return result
If the optimal value is never reached during the loop, the final result after processing all bits is returned.
return result
Edge Cases Handled
When the input list contains a single unique element, the set nums will have size one, and the inner loop that builds the prefix set will terminate after adding that single prefix. The subsequent check for a complementary prefix will fail, leaving result at its initial value of zero, which correctly reflects that no pair exists to produce a non-zero XOR.
If all numbers are identical, the mask construction still proceeds, but the prefix set never grows beyond one element. The early-exit condition len(one) == most will never be satisfied because most starts at two, ensuring the loop continues without unnecessary work. The final XOR remains zero, matching the expectation for identical inputs.
When the list includes the maximum possible integer for the given bit width, high.bit_length() captures the correct number of bits, and the mask expands to cover all relevant positions. The calculation of optimal accounts for the extra bit position, guaranteeing that the early-exit when result == optimal triggers only when the absolute maximum XOR is truly attainable.
Performance Optimizations
The conversion of the input list to a set eliminates duplicate values up front, reducing the number of elements processed in subsequent loops. This also enables constant-time membership checks when testing for the existence of a complementary prefix.
The variable most tracks the theoretical maximum number of distinct prefixes for the current bit width (2, 4, 8, …). By breaking out of the prefix-building loop once this count is reached, the algorithm avoids scanning the entire set when all possible prefixes are already present, saving iterations especially for large input sizes.
The mask is built incrementally using bitwise OR with the current bit value, allowing the algorithm to reuse previously computed masks without recomputing from scratch each iteration.
The early-exit condition that compares result with optimal provides a shortcut when the best possible XOR has been found. Since optimal represents the highest value achievable given the bit length, reaching it means no further processing can improve the answer, and the function returns immediately.
By iterating bits in descending order, the algorithm ensures that higher-order bits are fixed first, which reduces the search space for lower bits. This top-down approach means that once a higher bit is set in the result, lower bits are only considered in the context of that already-established prefix, limiting unnecessary checks.
ELI5 - Simplified Explanation
Imagine having a big box of numbers and wanting to pick two of them to play a special game where they combine in a secret way to make the biggest number possible. This code starts by looking at the numbers and figuring out how big the largest one is, which helps determine how many pieces of information each number holds.
It starts from the left side of the numbers, looking at the biggest pieces first. The code creates a mask that helps peek at specific parts of the numbers one by one. It keeps a record of the bits it has looked at so far and tries to see if it can build a bigger result by testing different combinations.
For every step, it checks if a certain target number can be formed by mixing the numbers available. If it finds two pieces that fit together to create a larger number, it saves that as the new goal. It keeps repeating this process, moving bit by bit toward the right until it has explored everything. The final goal is to find the pair that makes the largest possible value through this bitwise mystery.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1707: Maximum XOR With an Element From Array
- problem 2317: Maximum XOR After Operations
- problem 2416: Sum of Prefix Scores of Strings
- problem 2429: Minimize XOR
- problem 2932: Maximum Strong Pair XOR I
- problem 2935: Maximum Strong Pair XOR II
Solved On The Same Day
- problem 523: Continuous Subarray Sum
- problem 391: Perfect Rectangle
- problem 407: Trapping Rain Water II
- problem 479: Largest Palindrome Product
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality