Minimum and Maximum Xor Value Pair
Minimum and Maximum Xor Value Pair in C++
The problem asks us to find the minimum and maximum xor value possible from the elements provided we take only two elements. With this problem we cover how to apply trie in problems in which we have to do some binary operations.
Here is a detailed explanation and implementation in C++ for the problem.
Minimum and Maximum Xor Value Problem Description
We are given n integers and have to return the maximum and minimum xor value pair possible. We have to output the required values.
Example :
n = 3
The integer array is [1, 2, 3].
The output should be:
Max Xor pair possible 3
Min Xor pair possible 1
Explanation:
3 is obtained by bit wise xor of 1 and 2.
1 is obtained by bit wise xor of 2 and 3.
Minimum and Maximum Xor Value Solution Explanation
Naive Solution
The basic or naive approach is to use two nested loops and compute xor values for every pair possible and update minimum and & maximum xor value.
The time complexity of this approach is O(n^2). Which will time out if n > 10^4.
Code for naive approach is implemented below.
C++ Code
Output:
Max Xor pair possible 61
Min Xor pair possible 1
Optimized Solution
The optimized solution uses trie. We create a trie with node structure which points to only two child nodes 0 bit and one bit. We add the numbers in binary format in the trie from maximum bit (Integer limit , varies according to the constraints) to minimum bit ( ie 0). Then we will calculate the minimum and maximum xor value pair using the trie.
The time complexity – O(nlog(max(arr value)))
Below image with help you visualize how trie is created.
C++ Code
Output:
Max Xor pair possible 61
Min Xor pair possible 1
Login/Signup to comment