LeetCode Problem Workspace

Maximum XOR of Two Numbers in an Array

Find the maximum XOR of two numbers in an integer array using efficient bit manipulation techniques.

category

4

Topics

code_blocks

5

Code langs

hub

3

Related

Practice Focus

Medium · Array scanning plus hash lookup

bolt

Answer-first summary

Find the maximum XOR of two numbers in an integer array using efficient bit manipulation techniques.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array scanning plus hash lookup

Try AiBox Copilotarrow_forward

This problem asks for the maximum XOR value that can be obtained between any two numbers in an array. You need to efficiently use bit manipulation, hash tables, and array scanning to solve this problem within time constraints, especially for large arrays.

Problem Statement

Given an integer array nums, your task is to return the maximum value of nums[i] XOR nums[j], where 0 <= i <= j < n. The XOR operation yields a number that has binary digits set to 1 where the corresponding bits of the operands differ. The goal is to maximize this XOR result from any pair of numbers in the array.

For example, consider the array nums = [3,10,5,25,2,8]. The maximum XOR value can be obtained from the pair 5 and 25, which results in 28.

Examples

Example 1

Input: nums = [3,10,5,25,2,8]

Output: 28

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

Example details omitted.

Constraints

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

Solution Approach

Bitwise Trie Optimization

A trie (prefix tree) can be constructed from the binary representations of the numbers in the array. As you scan the array, you insert each number into the trie while simultaneously checking for the maximum XOR that can be formed with the current number. This takes advantage of bitwise operations to find optimal pairs efficiently.

Array Scanning with Hash Lookup

Scan the array from left to right and, at each step, maintain a hash set of previously seen numbers. For each number, compute its XOR with every previously seen number and update the maximum result. This method reduces the problem to a more efficient look-up approach, avoiding the need to compute XOR for all pairs.

Greedy Approach with Bit Manipulation

Use bit manipulation in a greedy fashion to maximize the XOR result. Start with the most significant bit and try to make the XOR as large as possible by considering potential numbers that could generate a larger result for each bit. This approach works efficiently in conjunction with a trie structure.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

The time complexity of the solution depends on the approach chosen. For the trie-based solution, the time complexity is O(n * L), where n is the number of elements in the array and L is the number of bits in each integer (typically 32). For the array scanning with hash lookup approach, the time complexity can vary but can be made to run in O(n * L). The space complexity for the trie is O(n * L), and for the hash lookup approach, it is O(n).

What Interviewers Usually Probe

  • Candidate can demonstrate knowledge of bitwise operations and their applications in optimization problems.
  • Candidate shows ability to use a trie structure for efficient lookups and optimizations.
  • Candidate understands the trade-offs between different approaches in terms of time and space complexity.

Common Pitfalls or Variants

Common pitfalls

  • Not considering the importance of bit-level operations, which can lead to inefficient brute force solutions.
  • Failing to optimize the space complexity when using a hash set or trie to store intermediate results.
  • Overlooking edge cases, such as arrays with only one element or arrays containing only the same number.

Follow-up variants

  • Solving the problem without using a trie, relying solely on hash-based solutions.
  • Modifying the problem to consider an array of very large numbers, affecting time complexity.
  • Finding the maximum XOR value for subarrays instead of the entire array.

FAQ

What is the optimal approach to solving the Maximum XOR of Two Numbers in an Array problem?

The optimal approach combines bit manipulation with a trie data structure or a hash set to efficiently compute the maximum XOR value in O(n * L) time.

How do I reduce the time complexity for Maximum XOR of Two Numbers in an Array?

To reduce time complexity, use a trie or hash set for faster lookups, avoiding the need to check every pair of numbers.

What is the trade-off between using a hash table versus a trie for this problem?

Using a hash table may offer a simpler solution but can be less efficient in terms of space, while a trie can provide a more structured and efficient space-time trade-off.

How does bitwise XOR work in this problem?

XOR compares the binary representation of two numbers and returns a result where each bit is 1 if the bits of the two numbers differ, and 0 if they are the same.

What are some edge cases I should consider when solving this problem?

Edge cases include arrays with only one element, arrays with identical elements, and ensuring the algorithm handles large arrays efficiently.

terminal

Solution

Solution 1

#### Python3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Trie:
    __slots__ = ("children",)

    def __init__(self):
        self.children: List[Trie | None] = [None, None]

    def insert(self, x: int):
        node = self
        for i in range(30, -1, -1):
            v = x >> i & 1
            if node.children[v] is None:
                node.children[v] = Trie()
            node = node.children[v]

    def search(self, x: int) -> int:
        node = self
        ans = 0
        for i in range(30, -1, -1):
            v = x >> i & 1
            if node.children[v ^ 1]:
                ans |= 1 << i
                node = node.children[v ^ 1]
            else:
                node = node.children[v]
        return ans


class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        trie = Trie()
        for x in nums:
            trie.insert(x)
        return max(trie.search(x) for x in nums)
Maximum XOR of Two Numbers in an Array Solution: Array scanning plus hash lookup | LeetCode #421 Medium