Maximum XOR of Two Numbers in an Array
Last Updated :
12 Jul, 2025
Given an array arr[] of non-negative integers. The task is to find the maximum possible XOR of any two elements of the array.
Example:
Input: arr[] = [26, 100, 25, 13, 4, 14]
Output: 126
Explanation: XOR of 26 ^ 100 = 126, which is the maximum possible XOR.
Input: arr[] = [1, 2, 3, 4, 5, 6, 7]
Output: 7
Explanation: XOR of 1 ^ 6 = 7, which is the maximum possible XOR.
[Naive Approach] Using 2 Nested Loops - O(n^2) Time and O(1) Space
The idea is to generate all possible pairs of elements of the array arr[] and find the maximum among them. To do so, use two nested loops to generate all the pairs and compute XOR of them. The maximum of all the pairs is the result.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum XOR
int maxXor(vector<int> &arr) {
int res = 0;
int fir = 0, sec = 0;
// Generate all possible pairs
for (int i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++) {
if((arr[i]^arr[j]) > res){
res = max(res, arr[i] ^ arr[j]);
fir = arr[i], sec = arr[j];
}
}
}
return res;
}
int main() {
vector<int> arr = {26, 100, 25, 13, 4, 14};
cout << maxXor(arr);
return 0;
}
Java
class GfG {
// Function to find the maximum XOR
static int maxXor(int[] arr) {
int res = 0;
// Generate all possible pairs
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
res = Math.max(res, arr[i] ^ arr[j]);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {26, 100, 25, 13, 4, 14};
System.out.println(maxXor(arr));
}
}
Python
# Function to find the maximum XOR
def maxXor(arr):
res = 0
# Generate all possible pairs
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
res = max(res, arr[i] ^ arr[j])
return res
if __name__ == "__main__":
arr = [26, 100, 25, 13, 4, 14]
print(maxXor(arr))
C#
using System;
class GfG {
// Function to find the maximum XOR
static int maxXor(int[] arr) {
int res = 0;
// Generate all possible pairs
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
res = Math.Max(res, arr[i] ^ arr[j]);
}
}
return res;
}
static void Main(string[] args) {
int[] arr = {26, 100, 25, 13, 4, 14};
Console.WriteLine(maxXor(arr));
}
}
JavaScript
// Function to find the maximum XOR
function maxXor(arr) {
let res = 0;
// Generate all possible pairs
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
res = Math.max(res, arr[i] ^ arr[j]);
}
}
return res;
}
let arr = [26, 100, 25, 13, 4, 14];
console.log(maxXor(arr));
[Expected Approach - 1] - Using Bit Masking and HashSet - O(n * log m) Time and O(n * log m) Space
The idea is to find two numbers in an array arr[] such that their XOR equals a number X, where X is the maximum value we want to achieve at the current bit position (i-th bit). To achieve the largest XOR value, we aim to maximize the number of 1s in the XOR result, starting from the most significant bit (leftmost bit) to the least significant bit (rightmost bit).
To evaluate each bit position, we use a mask. A mask helps us focus on specific bits of the numbers in the array by keeping only the relevant bits up to the current position and ignoring the rest. Using the mask, we extract prefixes for all numbers in the array (i.e., the portions of the numbers defined by the mask). These prefixes help us determine if a pair of numbers exists in the array whose XOR can yield a maximum value at the current bit.
For each bit position:
- Apply the mask to extract prefixes from the numbers.
- Try to update the maximum XOR value by assuming the i-th bit of the result is 1.
- Using the set of prefixes, we check if any two prefixes can produce the desired XOR value (with the i-th bit set).
This process is repeated for all 32 bits, starting from the leftmost bit, to compute the largest possible XOR value step by step.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum XOR
int maxXor(vector<int> &arr) {
int res = 0, mask = 0;
// to store all unique bits
unordered_set<int> s;
for (int i = 30; i >= 0; i--) {
// set the i-th bit in mask
mask |= (1 << i);
for (auto value: arr) {
// keep prefix of all elements
// till the i-th bit
s.insert(value & mask);
}
int cur = res | (1 << i);
for (int prefix : s) {
if (s.count(cur ^ prefix)) {
res = cur;
break;
}
}
s.clear();
}
return res;
}
int main() {
vector<int> arr = {26, 100, 25, 13, 4, 14};
cout << maxXor(arr);
return 0;
}
Java
import java.util.HashSet;
class GfG {
// Function to find the maximum XOR
static int maxXor(int[] arr) {
int res = 0, mask = 0;
// to store all unique bits
HashSet<Integer> s = new HashSet<>();
for (int i = 30; i >= 0; i--) {
// set the i-th bit in mask
mask |= (1 << i);
for (int value : arr) {
// keep prefix of all elements
// till the i-th bit
s.add(value & mask);
}
int cur = res | (1 << i);
for (int prefix : s) {
if (s.contains(cur ^ prefix)) {
res = cur;
break;
}
}
s.clear();
}
return res;
}
public static void main(String[] args) {
int[] arr = {26, 100, 25, 13, 4, 14};
System.out.println(maxXor(arr));
}
}
Python
# Function to find the maximum XOR
def maxXor(arr):
res = 0
mask = 0
# to store all unique bits
s = set()
for i in range(30, -1, -1):
# set the i-th bit in mask
mask |= (1 << i)
for num in arr:
# keep prefix of all elements
# till the i-th bit
s.add(num & mask)
cur = res | (1 << i)
for prefix in s:
if cur ^ prefix in s:
res = cur
break
s.clear()
return res
if __name__ == "__main__":
arr = [26, 100, 25, 13, 4, 14]
print(maxXor(arr))
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to find the maximum XOR
static int maxXor(int[] arr) {
int res = 0, mask = 0;
// to store all unique bits
HashSet<int> s = new HashSet<int>();
for (int i = 30; i >= 0; i--) {
// set the i-th bit in mask
mask |= (1 << i);
foreach (int value in arr) {
// keep prefix of all elements
// till the i-th bit
s.Add(value & mask);
}
int cur = res | (1 << i);
foreach (int prefix in s) {
if (s.Contains(cur ^ prefix)) {
res = cur;
break;
}
}
s.Clear();
}
return res;
}
static void Main(string[] args) {
int[] arr = {26, 100, 25, 13, 4, 14};
Console.WriteLine(maxXor(arr));
}
}
JavaScript
// Function to find the maximum XOR
function maxXor(arr) {
let res = 0, mask = 0;
// to store all unique bits
let s = new Set();
for (let i = 30; i >= 0; i--) {
// set the i-th bit in mask
mask |= (1 << i);
for (let num of arr) {
// keep prefix of all elements
// till the i-th bit
s.add(num & mask);
}
let cur = res | (1 << i);
for (let prefix of s) {
if (s.has(cur ^ prefix)) {
res = cur;
break;
}
}
s.clear();
}
return res;
}
let arr = [26, 100, 25, 13, 4, 14];
console.log(maxXor(arr));
Time Complexity: O(n * log m), where n is the size of array and m is the maximum element.
Auxiliary Space: O(n * log m)
[Expected Approach - 2] - Using Trie - O(n * log m) Time and O(n * log m) Space
The idea is to use Trie data structure to effectively store and search bits of each element of array arr[]. For each element arr[i], check if an element with opposite bits is present in the Trie or not i.e. if current bit of arr[i] is set (1), then check if unset bit (0) at current index is present in Trie.
Note: Please refer to Trie article to know more about insert and search operation.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
Node* one;
Node* zero;
Node() {
one = nullptr;
zero = nullptr;
}
};
class Trie {
public:
Node* root;
Trie() {
root = new Node();
}
// Function to insert in Trie
void insert(int n) {
Node* curr = root;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
// Check if the bit is 0
if (bit == 0) {
if (curr->zero == NULL) {
curr->zero = new Node();
}
curr = curr->zero;
}
// Else if bit is 1
else {
if (curr->one == NULL) {
curr->one = new Node();
}
curr = curr->one;
}
}
}
// Function to find element having
// the maximum XOR with value n
int findXOR(int n) {
Node* curr = root;
int res = 0;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
// if the bit is 0
if (bit == 0) {
// if set bit is present
if (curr->one) {
curr = curr->one;
res += (1 << i);
}
else {
curr = curr->zero;
}
}
// Else if bit is 1
else {
// if unset bit is present
if (curr->zero) {
curr = curr->zero;
res += (1 << i);
}
else {
curr = curr->one;
}
}
}
return res;
}
};
// Function to find the maximum XOR
int maxXor(vector<int> &arr) {
int res = 0;
Trie *t = new Trie();
// insert the first element in trie
t->insert(arr[0]);
for (int i = 1; i < arr.size(); i++) {
res = max(t->findXOR(arr[i]), res);
t->insert(arr[i]);
}
return res;
}
int main() {
vector<int> arr = {26, 100, 25, 13, 4, 14};
cout << maxXor(arr);
return 0;
}
Java
// Java program to find the maximum
// XOR n of two elements in an array
// using Trie data structure
import java.util.*;
class Node {
Node one;
Node zero;
Node() {
one = null;
zero = null;
}
}
class Trie {
Node root;
Trie() {
root = new Node();
}
// Function to insert in Trie
void insert(int n) {
Node curr = root;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
// Check if the bit is 0
if (bit == 0) {
if (curr.zero == null) {
curr.zero = new Node();
}
curr = curr.zero;
}
// Else if bit is 1
else {
if (curr.one == null) {
curr.one = new Node();
}
curr = curr.one;
}
}
}
// Function to find element having
// the maximum XOR with value n
int findXOR(int n) {
Node curr = root;
int res = 0;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
// if the bit is 0
if (bit == 0) {
// if set bit is present
if (curr.one != null) {
curr = curr.one;
res += (1 << i);
}
else {
curr = curr.zero;
}
}
// Else if bit is 1
else {
// if unset bit is present
if (curr.zero != null) {
curr = curr.zero;
res += (1 << i);
}
else {
curr = curr.one;
}
}
}
return res;
}
}
class GfG {
// Function to find the maximum XOR
static int maxXor(int[] arr) {
int res = 0;
Trie t = new Trie();
// insert the first element in trie
t.insert(arr[0]);
for (int i = 1; i < arr.length; i++) {
res = Math.max(t.findXOR(arr[i]), res);
t.insert(arr[i]);
}
return res;
}
public static void main(String[] args) {
int[] arr = {26, 100, 25, 13, 4, 14};
System.out.println(maxXor(arr));
}
}
Python
# Python program to find the maximum
# XOR n of two elements in an array
# using Trie data structure
class Node:
def __init__(self):
self.one = None
self.zero = None
class Trie:
def __init__(self):
self.root = Node()
# Function to insert in Trie
def insert(self, n):
curr = self.root
for i in range(31, -1, -1):
bit = (n >> i) & 1
# Check if the bit is 0
if bit == 0:
if not curr.zero:
curr.zero = Node()
curr = curr.zero
# Else if bit is 1
else:
if not curr.one:
curr.one = Node()
curr = curr.one
# Function to find element having
# the maximum XOR with value n
def findXOR(self, n):
curr = self.root
res = 0
for i in range(31, -1, -1):
bit = (n >> i) & 1
# if the bit is 0
if bit == 0:
# if set bit is present
if curr.one:
curr = curr.one
res += (1 << i)
else:
curr = curr.zero
# Else if bit is 1
else:
# if unset bit is present
if curr.zero:
curr = curr.zero
res += (1 << i)
else:
curr = curr.one
return res
# Function to find the maximum XOR
def maxXor(arr):
res = 0
t = Trie()
# insert the first element in trie
t.insert(arr[0])
for i in range(1, len(arr)):
res = max(t.findXOR(arr[i]), res)
t.insert(arr[i])
return res
if __name__ == "__main__":
arr = [26, 100, 25, 13, 4, 14]
print(maxXor(arr))
C#
// C# program to find the maximum
// XOR n of two elements in an array
// using Trie data structure
using System;
class Node {
public Node one;
public Node zero;
public Node() {
one = null;
zero = null;
}
}
class Trie {
public Node root;
public Trie() {
root = new Node();
}
// Function to insert in Trie
public void insert(int n) {
Node curr = root;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
// Check if the bit is 0
if (bit == 0) {
if (curr.zero == null) {
curr.zero = new Node();
}
curr = curr.zero;
}
// Else if bit is 1
else {
if (curr.one == null) {
curr.one = new Node();
}
curr = curr.one;
}
}
}
// Function to find element having
// the maximum XOR with value n
public int findXOR(int n) {
Node curr = root;
int res = 0;
for (int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
// if the bit is 0
if (bit == 0) {
// if set bit is present
if (curr.one != null) {
curr = curr.one;
res += (1 << i);
}
else {
curr = curr.zero;
}
}
// Else if bit is 1
else {
// if unset bit is present
if (curr.zero != null) {
curr = curr.zero;
res += (1 << i);
}
else {
curr = curr.one;
}
}
}
return res;
}
}
class GfG {
// Function to find the maximum XOR
static int maxXor(int[] arr) {
int res = 0;
Trie t = new Trie();
// insert the first element in trie
t.insert(arr[0]);
for (int i = 1; i < arr.Length; i++) {
res = Math.Max(t.findXOR(arr[i]), res);
t.insert(arr[i]);
}
return res;
}
static void Main(string[] args) {
int[] arr = {26, 100, 25, 13, 4, 14};
Console.WriteLine(maxXor(arr));
}
}
JavaScript
// JavaScript program to find the maximum
// XOR n of two elements in an array
// using Trie data structure
class Node {
constructor() {
this.one = null;
this.zero = null;
}
}
class Trie {
constructor() {
this.root = new Node();
}
// Function to insert in Trie
insert(n) {
let curr = this.root;
for (let i = 31; i >= 0; i--) {
let bit = (n >> i) & 1;
// Check if the bit is 0
if (bit === 0) {
if (!curr.zero) {
curr.zero = new Node();
}
curr = curr.zero;
}
// Else if bit is 1
else {
if (!curr.one) {
curr.one = new Node();
}
curr = curr.one;
}
}
}
// Function to find element having
// the maximum XOR with value n
findXOR(n) {
let curr = this.root;
let res = 0;
for (let i = 31; i >= 0; i--) {
let bit = (n >> i) & 1;
// if the bit is 0
if (bit === 0) {
// if set bit is present
if (curr.one) {
curr = curr.one;
res += (1 << i);
}
else {
curr = curr.zero;
}
}
// Else if bit is 1
else {
// if unset bit is present
if (curr.zero) {
curr = curr.zero;
res += (1 << i);
}
else {
curr = curr.one;
}
}
}
return res;
}
}
// Function to find the maximum XOR
function maxXOR(arr) {
let res = 0;
let t = new Trie();
// insert the first element in trie
t.insert(arr[0]);
for (let i = 1; i < arr.length; i++) {
res = Math.max(t.findXOR(arr[i]), res);
t.insert(arr[i]);
}
return res;
}
let arr = [26, 100, 25, 13, 4, 14];
console.log(maxXOR(arr));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem