Minimum XOR Value Pair
Last Updated :
17 Mar, 2023
Given an array of integers. Find the pair in an array that has a minimum XOR value.
Examples :
Input : arr[] = {9, 5, 3}
Output : 6
All pair with xor value (9 ^ 5) => 12,
(5 ^ 3) => 6, (9 ^ 3) => 10.
Minimum XOR value is 6
Input : arr[] = {1, 2, 3, 4, 5}
Output : 1
A Simple Solution is to generate all pairs of the given array and compute XOR their values. Finally, return minimum XOR value. This solution takes O(n2) time.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int minXOR( int arr[], int n)
{
int min_xor = INT_MAX;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++)
min_xor = min(min_xor, arr[i] ^ arr[j]);
return min_xor;
}
int main()
{
int arr[] = { 9, 5, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minXOR(arr, n) << endl;
return 0;
}
|
Java
class GFG {
static int minXOR( int arr[], int n)
{
int min_xor = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++)
for ( int j = i + 1 ; j < n; j++)
min_xor = Math.min(min_xor, arr[i] ^ arr[j]);
return min_xor;
}
public static void main(String args[])
{
int arr[] = { 9 , 5 , 3 };
int n = arr.length;
System.out.println(minXOR(arr, n));
}
}
|
Python3
def minXOR(arr, n):
arr.sort();
min_xor = 999999
val = 0
for i in range ( 0 , n - 1 ):
for j in range (i + 1 , n - 1 ):
val = arr[i] ^ arr[j]
min_xor = min (min_xor, val)
return min_xor
arr = [ 9 , 5 , 3 ]
n = len (arr)
print (minXOR(arr, n))
|
C#
using System;
class GFG {
static int minXOR( int [] arr, int n)
{
int min_xor = int .MaxValue;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++)
min_xor = Math.Min(min_xor, arr[i] ^ arr[j]);
return min_xor;
}
public static void Main()
{
int [] arr = { 9, 5, 3 };
int n = arr.Length;
Console.WriteLine(minXOR(arr, n));
}
}
|
PHP
<?php
function minXOR( $arr , $n )
{
$min_xor = PHP_INT_MAX;
for ( $i = 0; $i < $n ; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
$min_xor = min( $min_xor , $arr [ $i ] ^ $arr [ $j ]);
return $min_xor ;
}
$arr = array (9, 5, 3);
$n = count ( $arr );
echo minXOR( $arr , $n );
?>
|
Javascript
<script>
function minXOR(arr, n)
{
let min_xor = Number.MAX_VALUE;
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
min_xor = Math.min(min_xor, arr[i] ^ arr[j]);
return min_xor;
}
let arr = [ 9, 5, 3 ];
let n = arr.length;
document.write(minXOR(arr, n));
</script>
|
Space Complexity: O(1)
An Efficient solution can solve this problem in O(nlogn) time.
Algorithm:
- Sort the given array
- Traverse and check XOR for every consecutive pair
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minXOR( int arr[], int n)
{
sort(arr, arr + n);
int minXor = INT_MAX;
int val = 0;
for ( int i = 0; i < n - 1; i++) {
val = arr[i] ^ arr[i + 1];
minXor = min(minXor, val);
}
return minXor;
}
int main()
{
int arr[] = { 9, 5, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minXOR(arr, n) << endl;
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static int minXOR( int arr[], int n)
{
Arrays.parallelSort(arr);
int minXor = Integer.MAX_VALUE;
int val = 0 ;
for ( int i = 0 ; i < n - 1 ; i++) {
val = arr[i] ^ arr[i + 1 ];
minXor = Math.min(minXor, val);
}
return minXor;
}
public static void main(String args[])
{
int arr[] = { 9 , 5 , 3 };
int n = arr.length;
System.out.println(minXOR(arr, n));
}
}
|
Python3
import sys
def minXOR(arr, n):
arr.sort()
minXor = int (sys.float_info. max )
val = 0
for i in range ( 0 ,n - 1 ):
val = arr[i] ^ arr[i + 1 ];
minXor = min (minXor, val);
return minXor
arr = [ 9 , 5 , 3 ]
n = len (arr)
print (minXOR(arr, n))
|
C#
using System;
class GFG {
static int minXOR( int [] arr, int n)
{
Array.Sort(arr);
int minXor = int .MaxValue;
int val = 0;
for ( int i = 0; i < n - 1; i++) {
val = arr[i] ^ arr[i + 1];
minXor = Math.Min(minXor, val);
}
return minXor;
}
public static void Main()
{
int [] arr = { 9, 5, 3 };
int n = arr.Length;
Console.WriteLine(minXOR(arr, n));
}
}
|
PHP
<?php
function minXOR( $arr , $n )
{
sort( $arr );
$minXor = PHP_INT_MAX;
$val = 0;
for ( $i = 0; $i < $n - 1; $i ++)
{
$val = $arr [ $i ] ^ $arr [ $i + 1];
$minXor = min( $minXor , $val );
}
return $minXor ;
}
$arr = array (9, 5, 3);
$n = count ( $arr );
echo minXOR( $arr , $n );
?>
|
Javascript
<script>
function minXOR(arr, n)
{
arr.sort();
let minXor = Number.MAX_VALUE;
let val = 0;
for (let i = 0; i < n - 1; i++) {
val = arr[i] ^ arr[i + 1];
minXor = Math.min(minXor, val);
}
return minXor;
}
let arr = [ 9, 5, 3 ];
let n = arr.length;
document.write(minXOR(arr, n));
</script>
|
Time Complexity: O(N*logN)
Space Complexity: O(1)
A further more Efficient solution can solve the above problem in O(n) time under the assumption that integers take fixed number of bits to store. The idea is to use Trie Data Structure.
Algorithm:
- Create an empty trie. Every node of trie contains two children for 0 and 1 bits.
- Initialize min_xor = INT_MAX, insert arr[0] into trie
- Traversal all array element one-by-one starting from second.
- First find minimum setbet difference value in trie
- do xor of current element with minimum setbit diff that value
- update min_xor value if required
- insert current array element in trie
- return min_xor
Below is the implementation of above algorithm.
C++
#include <bits/stdc++.h>
using namespace std;
#define INT_SIZE 32
struct TrieNode {
int value;
TrieNode* Child[2];
};
TrieNode* getNode()
{
TrieNode* newNode = new TrieNode;
newNode->value = 0;
newNode->Child[0] = newNode->Child[1] = NULL;
return newNode;
}
void insert(TrieNode* root, int key)
{
TrieNode* temp = root;
for ( int i = INT_SIZE - 1; i >= 0; i--) {
bool current_bit = (key & (1 << i));
if (temp->Child[current_bit] == NULL)
temp->Child[current_bit] = getNode();
temp = temp->Child[current_bit];
}
temp->value = key;
}
int minXORUtil(TrieNode* root, int key)
{
TrieNode* temp = root;
for ( int i = INT_SIZE - 1; i >= 0; i--) {
bool current_bit = (key & (1 << i));
if (temp->Child[current_bit] != NULL)
temp = temp->Child[current_bit];
else if (temp->Child[1 - current_bit] != NULL)
temp = temp->Child[1 - current_bit];
}
return key ^ temp->value;
}
int minXOR( int arr[], int n)
{
int min_xor = INT_MAX;
TrieNode* root = getNode();
insert(root, arr[0]);
for ( int i = 1; i < n; i++) {
min_xor = min(min_xor, minXORUtil(root, arr[i]));
insert(root, arr[i]);
}
return min_xor;
}
int main()
{
int arr[] = { 9, 5, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minXOR(arr, n) << endl;
return 0;
}
|
Java
class GFG {
static final int INT_SIZE = 32 ;
static class TrieNode {
int value;
TrieNode[] Child = new TrieNode[ 2 ];
public TrieNode()
{
value = 0 ;
Child[ 0 ] = null ;
Child[ 1 ] = null ;
}
}
static TrieNode root;
static void insert( int key)
{
TrieNode temp = root;
for ( int i = INT_SIZE - 1 ; i >= 0 ; i--) {
int current_bit = (key & ( 1 << i)) >= 1 ? 1 : 0 ;
if (temp != null && temp.Child[current_bit] == null )
temp.Child[current_bit] = new TrieNode();
temp = temp.Child[current_bit];
}
temp.value = key;
}
static int minXORUtil( int key)
{
TrieNode temp = root;
for ( int i = INT_SIZE - 1 ; i >= 0 ; i--) {
int current_bit = (key & ( 1 << i)) >= 1 ? 1 : 0 ;
if (temp.Child[current_bit] != null )
temp = temp.Child[current_bit];
else if (temp.Child[ 1 - current_bit] != null )
temp = temp.Child[ 1 - current_bit];
}
return key ^ temp.value;
}
static int minXOR( int arr[], int n)
{
int min_xor = Integer.MAX_VALUE;
root = new TrieNode();
insert(arr[ 0 ]);
for ( int i = 1 ; i < n; i++) {
min_xor = Math.min(min_xor, minXORUtil(arr[i]));
insert(arr[i]);
}
return min_xor;
}
public static void main(String args[])
{
int arr[] = { 9 , 5 , 3 };
int n = arr.length;
System.out.println(minXOR(arr, n));
}
}
|
Python
class TrieNode:
def __init__( self ):
self .child = [ None ] * 2
self .value = None
class Trie:
def __init__( self ):
self .root = self .getNode()
def getNode( self ):
return TrieNode()
def insert( self ,key):
temp = self .root
for i in range ( 31 , - 1 , - 1 ):
curr = (key>>i)&( 1 )
if (temp.child[curr] is None ):
temp.child[curr] = self .getNode()
temp = temp.child[curr]
temp.value = key
def xorUtil( self ,key):
temp = self .root
for i in range ( 31 , - 1 , - 1 ):
curr = (key>>i)& 1
if (temp.child[curr] is not None ):
temp = temp.child[curr]
elif (temp.child[ 1 - curr] is not None ):
temp = temp.child[ 1 - curr]
return temp.value^key
def minXor(arr):
m = 2 * * 30
trie = Trie()
trie.insert(arr[ 0 ])
for i in range ( 1 , len (arr)):
m = min (m,trie.xorUtil(arr[i]))
trie.insert(arr[i])
return m
if __name__ = = "__main__" :
sample = [ 9 , 5 , 3 ]
print (minXor(sample))
|
C#
using System;
public class GFG
{
public const int INT_SIZE = 32;
public class TrieNode
{
public int value;
public TrieNode[] Child = new TrieNode[2];
public TrieNode()
{
this .value = 0;
this .Child[0] = null ;
this .Child[1] = null ;
}
}
public static TrieNode root;
public static void insert( int key)
{
var temp = root;
for ( int i = GFG.INT_SIZE - 1; i >= 0; i--)
{
var current_bit = (key & (1 << i)) >= 1 ? 1 : 0;
if (temp != null && temp.Child[current_bit] == null )
{
temp.Child[current_bit] = new TrieNode();
}
temp = temp.Child[current_bit];
}
temp.value = key;
}
public static int minXORUtil( int key)
{
var temp = root;
for ( int i = GFG.INT_SIZE - 1; i >= 0; i--)
{
var current_bit = (key & (1 << i)) >= 1 ? 1 : 0;
if (temp.Child[current_bit] != null )
{
temp = temp.Child[current_bit];
}
else if (temp.Child[1 - current_bit] != null )
{
temp = temp.Child[1 - current_bit];
}
}
return key ^ temp.value;
}
public static int minXOR( int [] arr, int n)
{
var min_xor = int .MaxValue;
root = new TrieNode();
GFG.insert(arr[0]);
for ( int i = 1; i < n; i++)
{
min_xor = Math.Min(min_xor,GFG.minXORUtil(arr[i]));
GFG.insert(arr[i]);
}
return min_xor;
}
public static void Main(String[] args)
{
int [] arr = {9, 5, 3};
var n = arr.Length;
Console.WriteLine(GFG.minXOR(arr, n));
}
}
|
Javascript
class TrieNode {
constructor() {
this .child = new Array(2);
this .value = null ;
}
}
class Trie {
constructor() {
this .root = this .getNode();
}
getNode() {
return new TrieNode();
}
insert(key) {
let temp = this .root;
for (let i = 31; i >= 0; i--) {
let curr = (key >> i) & 1;
if (!temp.child[curr]) temp.child[curr] = this .getNode();
temp = temp.child[curr];
}
temp.value = key;
}
xorUtil(key) {
let temp = this .root;
for (let i = 31; i >= 0; i--) {
let curr = (key >> i) & 1;
if (temp.child[curr]) temp = temp.child[curr];
else if (temp.child[1 - curr]) temp = temp.child[1 - curr];
}
return temp.value ^ key;
}
}
function minXor(arr) {
let m = 2 ** 30;
let trie = new Trie();
trie.insert(arr[0]);
for (let i = 1; i < arr.length; i++) {
m = Math.min(m, trie.xorUtil(arr[i]));
trie.insert(arr[i]);
}
return m;
}
if ( typeof module !== 'undefined' ) {
module.exports = {
minXor: minXor,
};
}
console.log(minXor([9, 5, 3]));
|
Time Complexity O(n)
Space Complexity: O(n*INT_SIZE)
Share your thoughts in the comments
Please Login to comment...