Minimum XOR Value Pair in C++



Problem statement

Given an array of integers. Find the pair in an array which has minimum XOR value

Example

If arr[] = {10, 20, 30, 40} then minimum value pair will be 20 and 30 as (20 ^ 30) = 10. (10 ^ 20) = 30 (10 ^ 30) = 20 (10 ^ 40) = 34 (20 ^ 30) = 10 (20 ^ 40) = 60 (30 ^ 40) = 54

Algorithm

  • Generate all pairs of given array and compute XOR their values
  • Return minimum XOR value

Example

 Live Demo

#include <bits/stdc++.h> using namespace std; int getMinValue(int *arr, int n) {    int minValue = INT_MAX;    for (int i = 0; i < n; ++i) {       for (int j = i + 1; j < n; ++j) {          minValue = min(minValue, arr[i] ^ arr[j]);       }    }    return minValue; } int main() {    int arr[] = {10, 20, 30, 40};    int n = sizeof(arr) / sizeof(arr[0]);    cout << "Minimum value = " << getMinValue(arr, n) << endl;    return 0; }

When you compile and execute above program. It generates following output −

Output

Minimum value = 10
Updated on: 2019-12-20T10:21:42+05:30

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements