1+ /*
2+ Given an integer array nums, return the maximum result of nums[i] XOR nums[j],
3+ where 0 ≤ i ≤ j < n.
4+ */
5+
6+ #include < iostream>
7+ #include < vector>
8+ using namespace std ;
9+
10+ // Constructing a trie
11+ struct trie {
12+ trie *zero,*one;
13+ };
14+
15+ // Building the trie
16+ void insert (int num,trie *root) {
17+ // Store the head
18+ trie *ptr=root;
19+ for (int i=31 ;i>=0 ;i--) {
20+ // Find the i-th bit
21+ int h = (num>>i & 1 );
22+ if (h==0 ) {
23+ // If ptr->zero is NULL
24+ if (ptr->zero ==NULL ) {
25+ ptr->zero =new trie ();
26+ }
27+ // Update ptr to ptr->zero
28+ ptr=ptr->zero ;
29+ }
30+ else {
31+ // If ptr->onr is NULL
32+ if (ptr->one ==NULL ) {
33+ ptr->one =new trie ();
34+ }
35+ // Update ptr to ptr->one
36+ ptr=ptr->one ;
37+ }
38+ }
39+ }
40+
41+ // Finding the maximum XOR for each element
42+ int comp (int num,trie *root) {
43+ trie *ptr = root;
44+ int sum=0 ;
45+ for (int i=31 ;i>=0 ;i--) {
46+ sum=sum<<1 ;
47+ // Finding ith bit
48+ int h = (num>>i & 1 );
49+ // Check if the bit is 0
50+ if (h==0 ) {
51+ // If right node exists
52+ if (ptr->one ) {
53+ sum++;
54+ ptr=ptr->one ;
55+ }
56+ else ptr=ptr->zero ;
57+
58+ }
59+ else {
60+ // Check if left node exists
61+ if (ptr->zero ) {
62+ sum++;
63+ ptr=ptr->zero ;
64+ }
65+ else ptr=ptr->one ;
66+ }
67+ }
68+ return sum;
69+ }
70+
71+ int findMaximumXOR (vector<int >& nums) {
72+ // head Node of Trie
73+ trie *root = new trie ();
74+ // Insert each element in trie
75+ for (int i=0 ;i<nums.size ();i++) {
76+ insert (nums[i],root);
77+ }
78+ // Stores the maximum XOR value
79+ int maxm=0 ;
80+ // Traverse the given array
81+ for (int i=0 ;i<nums.size ();i++) {
82+ maxm=max (comp (nums[i],root),maxm);
83+ }
84+ return maxm;
85+ }
86+
87+ // Main Function
88+ int main () {
89+
90+ vector<int >nums;
91+ int sz;
92+
93+ cout<<" Enter the vector size\n " ;
94+ cin>>sz; // size of the vector
95+
96+ cout<<" Enter the elements in the vector\n " ;
97+ for (int i=0 ;i<sz;i++) {
98+ int x;
99+ cin>>x;
100+ nums.push_back (x);
101+ }
102+
103+ int answer = findMaximumXOR (nums);
104+ cout<<" The Maximum XOR of two numbers in the array/vector is : " <<answer<<endl;
105+
106+ return 0 ;
107+ }
108+
109+ /* Sample Text Case
110+ Enter the vector size
111+ 6
112+ Enter the elements in the vector
113+ 3 10 5 25 2 8
114+ The Maximum XOR of two numbers in the array/vector is : 28
115+
116+ Time Complexity : O(n) , where n is the number of elements in the vector.
117+ */
0 commit comments