×

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java.

The objective is to enforce a value that indicates the least XOR values of the two numbers from a provided array of non-negative values.

Let us discuss a small example on obtaining the minimum XOR pair value.

Example 1:

Consider an array.

Input:  Arr[] = {1, 5, 10, 15}

Now let us find out the XOR value for each pair

(1 ^ 5) = 4

(1 ^ 10)= 11

(1 ^ 15) = 14

(5 ^ 10)= 15

(5 ^ 15) = 10

(10 ^ 15)= 5

From the above observation, the pair that has the least or minimum XOR value is 4

Output: 4

Example 2:

Consider an array

Input: arr[]= {2,4,6}

Now let us find out the XOR value for each pair

(2 ^ 4)= 6

(2 ^ 6)= 4

(4 ^ 6)= 2

From the above observation, the pair that has the least or minimum XOR value is 2

Output: 2

There are basically three ways in which the minimum XOR pair value is achieved. They probably are

  • Simple method
  • Sorting method
  • TRIE method

Simple Method

Finding every pair of elements existing in the given sequence is the simple strategy. Finding the smallest XOR value by computing the XOR for each pair. The generation of all the pairs in the provided array is a Simple Solution. Return the smallest possible XOR value. It takes this solution O(n2) time.

Let us understand the simple method with an example program

File name: Simplem.java

// A Java application to determine the least XOR output in an array.
Class Simlpem{


// Returns minimum XOR value of pair in arr[0..n-1]
static int minXOR(int arr[], int n)
{
int min_XOR = Integer.MAX_VALUE; // Initialize result


// Acquire each pair in the given array.
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)


// Update the least XOR value if necessary.
min_XOR = Math.min(min_XOR, arr[i] ^ arr[j]);


return min_XOR;
}
public static void main(String args[])
{
int arr[] = { 1,5,10,15 };
int n = arr.length;
System.out.println(minXOR(arr, n));
}
}

Output

4

Sorting Method

This method uses a single loop to obtain the minimal XOR value while sorting the input array. The reason the sorting strategy works is that the XOR for two integers that are close to one another has a lesser XOR value than the XOR for two integers that are far apart. Since the numbers that seem to be closer to just one another come following each other while sorting, all we need to do is execute a single loop to discover the XOR of the subsequent elements.

Let us understand it with a simple example program

File name: Sortm.java

import java.util.Arrays;
class Sortm {


// A method to determine the smallest XOR pair
static int minXOR(int arr[], int n)
{
// organizing the provided array
Arrays.parallelSort(arr);


int minXOR = Integer.MAX_VALUE;
int val = 0;


// generates the minimum XOR of the very next pairs.
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[] = { 2, 4, 6};
int n = arr.length;
System.out.println(minXOR(arr, n));
}
}

Output

2

TRIE Method

Since TRIE allows us to solve the problem faster than O(nlog(n)), we will obtain the most optimal result.

The following is the algorithm for the above method

  • Create an empty TRIE with two children per node, one for the 0 bit and the second for the 1 bit.
  • Add a[0] into TRIE after initialising minXORVal as INT MAX.
  • Beginning with the second element, go through each element of the array one at a time and complete the following:
  • Start by looking for the TRIE's standard minimum bit value difference. The current element is then XORed with the standard minimum bit that deviates from that value.
  • If necessary, update the minXORVal value.
  • Add the array's current element.
  • give the minXORVal back

Let us understand it with an example program

File name: Triem.java

// Java program to determine the array's minimal XOR value.
class Triem {
static final int INT_SIZE = 32;
static class TrieNode {
int value; // used in leaf node
TrieNode[] Child = new TrieNode[2];


public TrieNode()
{
value = 0;
Child[0] = null;
Child[1] = null;
}
}
static TrieNode root;


// utility function insert new key in trie
static void insert(int key)
{
TrieNode temp = root;
// Start with the most important bit and enter each essential bit one at a time into the trie
for (int i = INT_SIZE - 1; i >= 0; i--) {
// In the provided prefix, find the current bit.
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];
}


// continue to keep at leafNode
temp.value = key;
}
static int minXORUtil(int key)
{
TrieNode temp = root;


for (int i = INT_SIZE - 1; i >= 0; i--) {
// In the provided prefix, find the current bit.
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; // Initialize result


// make a True, then add the first element to it.
root = new TrieNode();
insert(arr[0]);


// For each number, iterate through all array elements to get the minimum XOR.
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[] = { 2, 4, 6};
int n = arr.length;
System.out.println(minXOR(arr, n));
}
}

Output

2

Related Topics

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.