Show problems as
Classic problem #421MediumArrayHash TableBit ManipulationTrie

Maximum XOR of Two Numbers in an Array

Real-world version: Largest Channel Spread
Tracked in this browser only
Read Maximum XOR of Two Numbers in an Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A lighting desk holds n fixtures. Fixture i is described by the non-negative integer nums[i], whose set bits say which channels that fixture drives.

Pair up two fixtures at positions i and j, where i and j may be the same position. The pair's spread is the number you get by combining the two descriptions with bitwise exclusive-or, so a bit of the spread is set exactly when one fixture of the pair drives that channel and the other does not.

Return the largest spread over all pairs. Pairing a fixture with itself gives a spread of 0, so a desk with a single fixture answers 0.

Examples

Example 1

Input
nums = [8, 10, 2]
Output
10

Pairing the fixtures at positions 0 and 2 gives `8 XOR 2 = 10`, the largest spread this desk reaches.

Example 2

Input
nums = [1024, 2048, 4096]
Output
6144

Each description has one bit set. Pairing 4096 with 2048 gives a spread of 6144, which is the largest here.

Example 3

Input
nums = [5, 5]
Output
0

Both fixtures drive the same channels, so every pair, including the two distinct positions, spreads to 0.

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • 0 <= nums[i] <= 2^31 - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def find_maximum_x_o_r(nums: list[int]) -> int:
Java
public int findMaximumXOR(int[] nums)