Back to problems Sign in to unlock
Leetcode
Medium
Arrays
Bit Manipulation
Tries
Google
Meta
Amazon
421. Maximum XOR of Two Numbers in an Array
Find the maximum XOR value obtainable by choosing any two numbers from an array.
Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.
Maximum XOR of Two Numbers in an Array
gfgPrimary
Problem Statement
Problem
Given an integer array nums, choose two different elements and compute their bitwise XOR. Return the largest XOR value you can obtain.
The two chosen elements may appear anywhere in the array, but they must be distinct indices.
Goal
Maximize:
[
nums[i] \oplus nums[j]
]
for all i != j.
Notes
- XOR compares numbers bit by bit.
- The answer is the maximum value, not the pair itself.
Input Format
- A single integer array
nums. - Each element is a non-negative integer.
Output Format
- Return one integer: the maximum XOR of any pair of distinct elements in
nums.
Constraints
2 <= nums.length0 <= nums[i](use the usual 32-bit integer range in practice)- Must choose two different indices
Examples
Sample cases returned by the problem API.
Example 1
Input
nums = [3, 10, 5, 25, 2, 8]
Output
28
Explanation
The best pair is 5 ^ 25 = 28.
Example 2
Input
nums = [0, 2, 5, 7]
Output
7
Explanation
One optimal pair is 2 ^ 5 = 7.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.