Skip to main content

Maximum XOR of Two Numbers in an Array - Solution & Explanation

MediumArrayHash TableBit ManipulationTrie17 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

 

Example 1:

Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.

Example 2:

Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127

 

Constraints:

  • 1 <= nums.length <= 2 * 105
  • 0 <= nums[i] <= 231 - 1

Approach Overview

Problem Overview: Given an integer array nums, you need to find two numbers whose XOR value is the largest possible. The challenge is identifying the pair that maximizes the XOR operation without checking every combination when the array becomes large.

Approach 1: Brute Force Pair Comparison (O(nΒ²) time, O(1) space)

The most direct strategy checks every possible pair in the array. Iterate through the array using two nested loops and compute nums[i] ^ nums[j] for each pair. Track the maximum value seen so far and return it after scanning all combinations. This method uses basic array traversal and bit manipulation operations.

The logic is easy to implement and useful for validating correctness on small datasets. However, the time complexity grows quickly because every element is compared with every other element. With n numbers, the algorithm performs roughly n*(n-1)/2 XOR operations, making it impractical for large inputs.

Approach 2: Trie-Based Bit Optimization (O(n * W) time, O(n * W) space)

A more efficient solution builds a binary Trie based on the bit representation of each number. Each level of the Trie represents a bit position (usually 31 down to 0 for 32‑bit integers). While inserting numbers, you store paths for 0 and 1 bits. To maximize XOR, traverse the Trie preferring the opposite bit at each level because XOR becomes 1 when bits differ.

For every number in the array, walk the Trie from the most significant bit to the least significant bit. If the current bit is 0, try moving to the 1 branch; if the bit is 1, try moving to the 0 branch. This greedy decision maximizes the resulting XOR value bit by bit. Each insertion and query touches at most W bits, where W is the integer bit length (typically 32).

The Trie structure allows you to efficiently search for the best complementary number already inserted. Instead of comparing against all elements, you narrow the search using bit decisions. The result is near-linear performance relative to the input size.

Recommended for interviews: Interviewers expect the Trie-based approach because it demonstrates strong understanding of bitwise operations and optimized search structures. Starting with the brute force approach shows you understand the problem baseline. Transitioning to the Trie solution shows algorithmic maturity and familiarity with advanced bitwise greedy strategies used in many XOR-related problems.

Approach 1: Brute Force Approach

This approach involves iterating over all possible pairs of numbers in the array and calculating their XOR. We keep track of the maximum XOR value encountered during these iterations.

Though straightforward, this method is not efficient for large arrays, as it involves checking each pair of numbers.

The function findMaximumXOR takes an integer array and its size as arguments. It iterates over all pairs of elements in the array, calculating the XOR for each pair and updating the maximum XOR found so far. Finally, it returns the maximum XOR value.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2), where n is the number of elements in the array, because it checks every pair.
Space Complexity: O(1), as it uses only a constant amount of space.

Try this approach in the editor β†’

Approach 2: Trie-Based Approach

This approach makes use of a Trie data structure to efficiently maximize the XOR computation. By examining the binary representation of numbers, we can leverage the Trie to only explore branches that potentially maximize the XOR result.

The Trie helps in finding complementary patterns (bits) efficiently by using bit manipulation and path traversal.

This solution constructs a Trie to store the binary representation of each number. As each number is inserted into the Trie, we simultaneously seek to maximize the XOR by traversing potentially complementing paths (opposite bits in Trie nodes).

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * W), where n is the number of elements and W is the number of bits in the maximum number.
Space Complexity: O(n * W), for storing the Trie.

Try this approach in the editor β†’

Approach 3: Default Approach

Code

Python

Java

C++

Go

Rust

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Brute Force Approach

Time Complexity: O(n^2), where n is the number of elements in the array, because it checks every pair.
Space Complexity: O(1), as it uses only a constant amount of space.

Trie-Based Approach

Time Complexity: O(n * W), where n is the number of elements and W is the number of bits in the maximum number.
Space Complexity: O(n * W), for storing the Trie.

Default Approachβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Pair ComparisonO(nΒ²)O(1)Small arrays or quick baseline solution to verify correctness
Trie-Based Bit OptimizationO(n * W) β‰ˆ O(n)O(n * W)Large arrays where near-linear performance is required

Video Solution

maximum xor of two numbers in an array leetcode | leetcode 421 | bitwise solution β€’ Naresh Gupta β€’ 26,529 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Maximum XOR of Two Numbers in an Array easy or hard?
Maximum XOR of Two Numbers in an Array is generally classified as a medium difficulty problem. The brute force idea is straightforward, but identifying the Trie-based optimization requires understanding of bit manipulation and prefix tree structures.
How to solve Maximum XOR of Two Numbers in an Array in O(n)?
Use a binary Trie to store the bit representation of numbers as you iterate through the array. For each number, traverse the Trie preferring the opposite bit at each position to maximize XOR. Since each number processes at most 32 bits, the overall complexity becomes O(n * 32), which is effectively linear.
Maximum XOR of Two Numbers in an Array Python or Java solution?
Python and Java solutions typically implement the Trie-based method. Each number is inserted bit by bit into the Trie, and another traversal searches for the best complementary bits to maximize XOR. The algorithm runs in O(n * W) time and works efficiently even for large arrays.
What is the best approach for Maximum XOR of Two Numbers in an Array?
The most efficient approach uses a binary Trie built from the bit representation of numbers. For each number, you traverse the Trie and try to match opposite bits to maximize XOR at every position. This greedy bit strategy produces the optimal result with O(n * W) time complexity, where W is the number of bits (typically 32).
Is Maximum XOR of Two Numbers in an Array asked at Google Amazon Meta?
Maximum XOR of Two Numbers in an Array appears in technical interview preparation lists for companies such as Google, Amazon, and Meta. The problem tests bit manipulation skills, greedy reasoning, and familiarity with Trie data structures for efficient bitwise search.
What data structure is used in Maximum XOR of Two Numbers in an Array?
The optimal solution uses a binary Trie (also called a prefix tree) where each node represents a bit value 0 or 1. This structure allows fast traversal to find numbers with complementary bits, which maximizes the XOR value during comparison.
What is the time complexity of Maximum XOR of Two Numbers in an Array?
The brute force solution runs in O(nΒ²) time because it compares every pair of elements. The optimized Trie-based approach runs in O(n * W) time, where W is the bit length of integers (usually 32). This effectively behaves like O(n) for typical constraints.

Ready to solve this problem?

Practice Maximum XOR of Two Numbers in an Array with our built-in code editor and test cases.

Practice on FleetCode