AlgoMaster Logo

Maximum XOR of Two Numbers in an Array

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

For the brute force method, we consider each possible pair of numbers in the array and calculate their XOR. The XOR operation will give us a number with bits set where the bits differ between the two numbers. Our task is to find the two numbers that maximize this XOR. This approach checks all pairs and picks the one with the maximum XOR value.

Steps:

  1. Initialize a variable maxXOR to zero.
  2. For every pair of numbers (A[i], A[j]) in the array, compute the XOR A[i] ^ A[j].
  3. Update maxXOR if the computed XOR is greater than maxXOR.
  4. Return maxXOR.

Code:

2. Optimal Approach Using Trie

Intuition:

The key idea is to use a Trie (prefix tree) to efficiently find two numbers in the array that can form the maximum XOR result. By inserting all numbers in the Trie and using bit manipulation, we can find pairs leading to maximum XOR efficiently. This relies on the fact that XOR tends to maximize when we have opposing bits (i.e., one bit is 0, the other is 1).

Steps:

  1. Define a Trie structure with only two children for each node, representing a bit of 0 or 1.
  2. Insert each number in the array into the Trie.
  3. As each number is inserted, simultaneously calculate the maximum XOR for that number with the previously inserted numbers in the Trie.
  4. Return the highest XOR obtained.

Code: