Data Structures19 sections · 729 units
Open in Course

Problem - Maximum XOR of Two Numbers

Bitwise trie application

Given an integer array nums, return the maximum result of nums[i] XOR nums[j]. Example: For [3,10,5,25,2,8][3, 10, 5, 25, 2, 8], the maximum XOR is 2828 (525=285 \oplus 25 = 28).

Naive approach: try all pairs in O(n2)O(n^2). The trie approach: store numbers as binary strings in a trie.

For each number, traverse the trie trying to go the opposite direction at each bit (maximizing XOR). Constraints: 11 to 21052 \cdot 10^5 numbers, each from 00 to 23112^{31} - 1.