Given an array arr[] of size N, the task is to split the array into two subsets such that the Bitwise XOR between the maximum of the first subset and minimum of the second subset is minimum.
Examples:
Input: arr[] = {3, 1, 2, 6, 4}
Output: 1
Explanation:
Splitting the given array in two subsets {1, 3}, {2, 4, 6}.
The maximum of the first subset is 3 and the minimum of the second subset is 2.
Therefore, their bitwise XOR is equal to 1.
Input: arr[] = {2, 1, 3, 2, 4, 3}
Output: 0
Approach: The idea is to find the two elements in the array such that the Bitwise XOR between the two array elements is minimum. Follow the steps below to solve the problem:
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int splitArray( int arr[], int N)
{
sort(arr, arr + N);
int result = INT_MAX;
for ( int i = 1; i < N; i++) {
result = min(result,
arr[i] - arr[i - 1]);
}
return result;
}
int main()
{
int arr[] = { 3, 1, 2, 6, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << splitArray(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int splitArray( int arr[], int N)
{
Arrays.sort(arr);
int result = Integer.MAX_VALUE;
for ( int i = 1 ; i < N; i++)
{
result = Math.min(result,
arr[i] - arr[i - 1 ]);
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 3 , 1 , 2 , 6 , 4 };
int N = arr.length;
System.out.print(splitArray(arr, N));
}
}
|
Python3
def splitArray(arr, N):
arr = sorted (arr)
result = 10 * * 9
for i in range ( 1 , N):
result = min (result, arr[i] ^ arr[i - 1 ])
return result
if __name__ = = '__main__' :
arr = [ 3 , 1 , 2 , 6 , 4 ]
N = len (arr)
print (splitArray(arr, N))
|
C#
using System;
class GFG{
static int splitArray( int []arr, int N)
{
Array.Sort(arr);
int result = Int32.MaxValue;
for ( int i = 1; i < N; i++)
{
result = Math.Min(result,
arr[i] ^ arr[i - 1]);
}
return result;
}
public static void Main()
{
int []arr = { 3, 1, 2, 6, 4 };
int N = arr.Length;
Console.Write(splitArray(arr, N));
}
}
|
Javascript
<script>
function splitArray(arr, N)
{
arr.sort();
let result = Number.MAX_VALUE;
for (let i = 1; i < N; i++) {
result = Math.min(result,
arr[i] - arr[i - 1]);
}
return result;
}
let arr = [ 3, 1, 2, 6, 4 ];
let N = arr.length;
document.write(splitArray(arr, N));
</script>
|
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
30 Apr, 2021
Like Article
Save Article