Binary trie
Time O(31 n) Space O(31 n)Insert each number's bits 30..0 into a trie stored in arrays. Then query: at each bit, move to the opposite bit if it exists (adding that bit to the result), else the same bit.
class Solution {
public int findMaximumXOR(int[] nums) {
int[][] next = new int[nums.length * 31 + 1][2];
int size = 1, best = 0;
for (int x : nums) {
int node = 0;
for (int b = 30; b >= 0; b--) {
int bit = (x >> b) & 1;
if (next[node][bit] == 0) next[node][bit] = size++;
node = next[node][bit];
}
int cur = 0, xor = 0;
for (int b = 30; b >= 0; b--) {
int bit = (x >> b) & 1;
if (next[cur][bit ^ 1] != 0) { xor |= 1 << b; cur = next[cur][bit ^ 1]; }
else cur = next[cur][bit];
}
best = Math.max(best, xor);
}
return best;
}
}Verdict: Linear in n.