[Geeks for Geeks] Maximum XOR of two numbers in an array

Maximum XOR of two numbers in an array

Given an array of non-negative integers of size N. Find the maximum possible XOR between two numbers present in the array.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
struct Trie {
Trie *next[2];
bool eof = false;

Trie() {
memset(next, 0, sizeof next);
}

void insert(int n, int mask = 20) {
if (mask == -1) eof = true;
else {
bool bit = n & (1 << mask);
if (!next[bit]) next[bit] = new Trie();
next[bit]->insert(n, mask - 1);
}
}

int query(int n, int mask = 20) {
if (mask == -1) return 0;
bool bit = n & (1 << mask);
if (next[!bit]) return (1 << mask) + next[!bit]->query(n, mask - 1);
if (next[bit]) return next[bit]->query(n, mask - 1);
return n & ((1 << (mask + 1)) - 1);
}
};

class Solution {
public:
int max_xor(int arr[], int n) {
Trie* t = new Trie();
t->insert(arr[0]);
int res = 0;
for(int i = 1; i < n; i++) {
res = max(res, t->query(arr[i]));
t->insert(arr[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/maximum-xor-of-two-numbers-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.