Maximum XOR of Two Numbers in an Array

MediumBit Manipulationtrie

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an array of non-negative integers nums, return the maximum value of nums[i] XOR nums[j] over all index pairs with 0 <= i <= j < nums.length. Because i may equal j, a single-element array returns 0. Aim for O(n * B) time where B is the number of bits (31 here), using a binary trie or a greedy bit-by-bit prefix search.

Examples

Input: nums = [8,1,2,12]
Output: 14
12 XOR 2 = 1100 XOR 0010 = 1110 = 14, the largest over all pairs.
Input: nums = [1,2,4]
Output: 6
2 XOR 4 = 6, while 1 XOR 4 = 5 and 1 XOR 2 = 3.
Input: nums = [7]
Output: 0
The only pair is (0, 0) and 7 XOR 7 = 0.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More trie problems