Value in a given range with maximum XOR
Last Updated :
16 Oct, 2023
Given positive integers N, L, and R, we have to find the maximum value of N ? X, where X ? [L, R].
Examples:
Input : N = 7
L = 2
R = 23
Output : 23
Explanation : When X = 16, we get 7 ? 16 = 23 which is the maximum value for all X ? [2, 23].
Input : N = 10
L = 5
R = 12
Output : 15
Explanation : When X = 5, we get 10 ? 5 = 15 which is the maximum value for all X ? [5, 12].
Brute force approach: We can solve this problem using brute force approach by looping over all integers over the range [L, R] and taking their XOR with N while keeping a record of the maximum result encountered so far. The complexity of this algorithm will be O(R - L), and it is not feasible when the input variables approach high values such as 109.
Efficient approach: Since the XOR of two bits is 1 if and only if they are complementary to each other, we need X to have complementary bits to that of N to have the maximum value. We will iterate from the largest bit (log2(R)th Bit) to the lowest (0th Bit). The following two cases can arise for each bit:
- If the bit is not set, i.e. 0, we will try to set it in X. If setting this bit to 1 results in X exceeding R, then we will not set it.
- If the bit is set, i.e. 1, then we will try to unset it in X. If the current value of X is already greater than or equal to L, then we can safely unset the bit. In the other case, we will check if setting all of the next bits is enough to keep X >= L. If not, then we are required to set the current bit. Observe that setting all the next bits is equivalent to adding (1 << b) - 1, where b is the current bit.
The time complexity of this approach is O(log2(R)).
C++
// CPP program to find the x in range [l, r]
// such that x ^ n is maximum.
#include <cmath>
#include <iostream>
using namespace std;
// Function to calculate the maximum value of
// N ^ X, where X is in the range [L, R]
int maximumXOR(int n, int l, int r)
{
int x = 0;
for (int i = log2(r); i >= 0; --i)
{
if (n & (1 << i)) // Set bit
{
if (x + (1 << i) - 1 < l)
x ^= (1 << i);
}
else // Unset bit
{
if ((x ^ (1 << i)) <= r)
x ^= (1 << i);
}
}
return n ^ x;
}
// Driver Code
int main()
{
int n = 7, l = 2, r = 23;
cout << "The output is " << maximumXOR(n, l, r);
return 0;
}
Java
// Java program to find the x in range [l, r]
// such that x ^ n is maximum.
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to calculate the maximum value of
// N ^ X, where X is in the range [L, R]
static int maximumXOR(int n, int l, int r)
{
int x = 0;
for (int i = (int)(Math.log(r)/Math.log(2)); i >= 0; --i)
{
if ((n & (1 << i))>0) // Set bit
{
if (x + (1 << i) - 1 < l)
x ^= (1 << i);
}
else // Unset bit
{
if ((x ^ (1 << i)) <= r)
x ^= (1 << i);
}
}
return n ^ x;
}
// Driver function
public static void main(String args[])
{
int n = 7, l = 2, r = 23;
System.out.println( "The output is " + maximumXOR(n, l, r));
}
}
// This code is Contributed by tufan_gupta2000
Python3
# Python program to find the
# x in range [l, r] such that
# x ^ n is maximum.
import math
# Function to calculate the
# maximum value of N ^ X,
# where X is in the range [L, R]
def maximumXOR(n, l, r):
x = 0
for i in range(int(math.log2(r)), -1, -1):
if (n & (1 << i)): # Set bit
if (x + (1 << i) - 1 < l):
x ^= (1 << i)
else: # Unset bit
if (x ^ (1 << i)) <= r:
x ^= (1 << i)
return n ^ x
# Driver code
n = 7
l = 2
r = 23
print("The output is",
maximumXOR(n, l, r))
# This code was contributed
# by VishalBachchas
C#
// C# program to find the x in range
// [l, r] such that x ^ n is maximum.
using System;
class GFG
{
// Function to calculate the
// maximum value of N ^ X,
// where X is in the range [L, R]
public static int maximumXOR(int n,
int l, int r)
{
int x = 0;
for (int i = (int)(Math.Log(r) /
Math.Log(2)); i >= 0; --i)
{
if ((n & (1 << i)) > 0) // Set bit
{
if (x + (1 << i) - 1 < l)
{
x ^= (1 << i);
}
}
else // Unset bit
{
if ((x ^ (1 << i)) <= r)
{
x ^= (1 << i);
}
}
}
return n ^ x;
}
// Driver Code
public static void Main(string[] args)
{
int n = 7, l = 2, r = 23;
Console.WriteLine("The output is " +
maximumXOR(n, l, r));
}
}
// This code is contributed
// by Shrikant13
JavaScript
<script>
// Javascript program to find
// the x in range [l, r]
// such that x ^ n is maximum.
// Function to calculate the maximum value of
// N ^ X, where X is in the range [L, R]
function maximumXOR(n, l, r)
{
let x = 0;
for (let i =
parseInt(Math.log(r) / Math.log(2)); i >= 0; --i)
{
if (n & (1 << i)) // Set bit
{
if (x + (1 << i) - 1 < l)
x ^= (1 << i);
}
else // Unset bit
{
if ((x ^ (1 << i)) <= r)
x ^= (1 << i);
}
}
return n ^ x;
}
// Driver Code
let n = 7, l = 2, r = 23;
document.write("The output is " + maximumXOR(n, l, r));
</script>
PHP
<?php
// PHP program to find the x in range
// [l, r] such that x ^ n is maximum.
// Function to calculate the maximum
// value of N ^ X, where X is in the
// range [L, R]
function maximumXOR($n, $l, $r)
{
$x = 0;
for ($i = log($r, 2); $i >= 0; --$i)
{
if ($n & (1 << $i))
{
// Set bit
if ($x + (1 << $i) - 1 < $l)
$x ^= (1 << $i);
}
else
{
// Unset bit
if (($x ^ (1 << $i)) <= $r)
$x ^= (1 << $i);
}
}
return $n ^ $x;
}
// Driver Code
$n = 7;
$l = 2;
$r = 23;
echo "The output is " ,
maximumXOR($n, $l, $r);
// This code is contributed by ajit
?>
Time complexity: O(log2r)
Auxiliary Space: O(1)
Approach#2: Using Brute Force
One way to solve this problem is to try all possible values of X in the given range and find the one that gives the maximum XOR value with N.
Algorithm
1. Define a function max_XOR(N, L, R) that takes N, L and R as input.
2. Initialize a variable max_XOR_val to 0.
3. For each value of X in the range [L, R], calculate the XOR value of N and X.
4. If the XOR value is greater than max_XOR_val, update max_XOR_val with this value.
5. Return max_XOR_val as the output.
C++
#include <iostream>
using namespace std;
int max_XOR(int N, int L, int R) {
int max_XOR_val = 0;
for (int X = L; X <= R; X++) {
int XOR_val = N ^ X;
if (XOR_val > max_XOR_val) {
max_XOR_val = XOR_val;
}
}
return max_XOR_val;
}
int main() {
int N = 7;
int L = 2;
int R = 23;
cout << max_XOR(N, L, R) << endl;
N = 10;
L = 5;
R = 12;
cout << max_XOR(N, L, R) << endl;
return 0;
}
Java
public class Main {
// Function to find the maximum XOR value between N and integers in the range [L, R]
public static int maxXOR(int N, int L, int R) {
int maxXORValue = 0;
for (int X = L; X <= R; X++) {
int XORValue = N ^ X; // Calculate the XOR value between N and X
if (XORValue > maxXORValue) {
maxXORValue = XORValue; // Update the maximum XOR value if a larger one is found
}
}
return maxXORValue;
}
public static void main(String[] args) {
int N = 7;
int L = 2;
int R = 23;
// Find and print the maximum XOR value for the given parameters
System.out.println( maxXOR(N, L, R));
N = 10;
L = 5;
R = 12;
// Find and print the maximum XOR value for the updated parameters
System.out.println( maxXOR(N, L, R));
}
}
Python3
def max_XOR(N, L, R):
max_XOR_val = 0
for X in range(L, R+1):
XOR_val = N ^ X
if XOR_val > max_XOR_val:
max_XOR_val = XOR_val
return max_XOR_val
# Example usage
N = 7
L = 2
R = 23
print(max_XOR(N, L, R))
N = 10
L = 5
R = 12
print(max_XOR(N, L, R))
C#
using System;
public class MainClass
{
// Function to find the maximum XOR value between N and integers in the range [L, R]
public static int MaxXOR(int N, int L, int R)
{
int maxXORValue = 0;
for (int X = L; X <= R; X++)
{
int XORValue = N ^ X; // Calculate the XOR value between N and X
if (XORValue > maxXORValue)
{
maxXORValue = XORValue; // Update the maximum XOR value if a larger one is found
}
}
return maxXORValue;
}
public static void Main(string[] args)
{
int N = 7;
int L = 2;
int R = 23;
// Find and print the maximum XOR value for the given parameters
Console.WriteLine(MaxXOR(N, L, R));
N = 10;
L = 5;
R = 12;
// Find and print the maximum XOR value for the updated parameters
Console.WriteLine(MaxXOR(N, L, R));
}
}
JavaScript
// Function to find the maximum XOR value between N and numbers in the range [L, R]
function max_XOR(N, L, R) {
// Variable to store the maximum XOR value
let max_XOR_val = 0;
// Iterate over the range [L, R]
for (let X = L; X <= R; X++) {
// Calculate the XOR value between N and X
let XOR_val = N ^ X;
// Update the maximum XOR value if necessary
if (XOR_val > max_XOR_val) {
max_XOR_val = XOR_val;
}
}
// Return the maximum XOR value
return max_XOR_val;
}
// Example usage
let N = 7;
let L = 2;
let R = 23;
console.log(max_XOR(N, L, R)); // Output: 31
N = 10;
L = 5;
R = 12;
console.log(max_XOR(N, L, R)); // Output: 15
Time Complexity: O(R-L+1)
Space Complexity: O(1)
Similar Reads
Find a value whose XOR with given number is maximum
Given a value X, the task is to find the number Y which will give maximum value possible when XOR with X. (Assume X to be 8 bits) Maximum possible value of X and Y is 255.Examples: Input: X = 2 Output: 253 Binary Representation of X = 00000010 Binary Representation of Y = 11111101 Maximum XOR value:
4 min read
Maximum XOR pair product with a given value
Given a positive integer value V, the task is to find the maximum XOR of two numbers such that their product is equal to the given value V. Examples: Input: V = 20Output: 7Explanation: For the given value of 20, there are several pairs of numbers whose product is 20: (1, 20), (2, 10), and (4, 5). Th
5 min read
Number whose sum of XOR with given array range is maximum
You are given a sequence of N integers and Q queries. In each query, you are given two parameters L and R. You have to find the smallest integer X such that 0 <= X < 2^31 and the sum of XOR of x with all elements in range [L, R] is maximum possible.Examples : Input : A = {20, 11, 18, 2, 13} Th
15+ min read
Maximum XOR value of a pair from a range
Given a range [L, R], we need to find two integers in this range such that their XOR is maximum among all possible choices of two integers. More Formally, given [L, R], find max (A ^ B) where L <= A, B Examples : Input : L = 8 R = 20 Output : 31 31 is XOR of 15 and 16. Input : L = 1 R = 3 Output
6 min read
Find the maximum subset XOR of a given set
Given a set of positive integers. find the maximum XOR subset value in the given set. Expected time complexity O(n).Examples:Input: set[] = {2, 4, 5}Output: 7The subset {2, 5} has maximum XOR valueInput: set[] = {9, 8, 5}Output: 13The subset {8, 5} has maximum XOR valueInput: set[] = {8, 1, 2, 12, 7
15+ min read
Maximum XOR value in matrix
Given a square matrix (N X N), the task is to find the maximum XOR value of a complete row or a complete column. Examples : Input : N = 3 mat[3][3] = {{1, 0, 4}, {3, 7, 2}, {5, 9, 10} }; Output : 14 We get this maximum XOR value by doing XOR of elements in second column 0 ^ 7 ^ 9 = 14 Input : N = 4
7 min read
Find the maximum subarray XOR in a given array
Given an array of integers. The task is to find the maximum subarray XOR value in the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 7Explanation: The subarray {3, 4} has maximum XOR value Input: arr[] = {8, 1, 2, 12, 7, 6}Output: 15Explanation: The subarray {1, 2, 12} has maximum XOR val
15+ min read
Smallest number whose set bits are maximum in a given range
Given a positive integer 'l' and 'r'. Find the smallest number 'n' such that l <= n <= r and count of the number of set bits(number of '1's in binary representation) is as maximum as possible. Examples : Input: 1 4Output: 3Explanation:Binary representation from '1' to '4':110 = 0012210 = 01023
9 min read
Maximum Sum of Array with given MEX
Given 3 integers N, K, and X, the task is to construct an array arr[] with the below conditions: Size of the array = NMEX of the array = KAll array elements should be at most XAmong all the array that follows the above condition print the one having the maximum sum of its elements or print -1 if no
7 min read
Find a value X in range [0, K] which can maximize X XOR sum over given array
Given an array a[] of size N and an integer K, the task is to find a value X in the range [0, K] which can maximize the value of the given function Xor-sum(X) = (X XOR A[0]) + (X Xor A[1]) + (X Xor A[2]) + __________+ (X Xor A[N-1]). Examples: Input: a[] = {1, 2, 3, 4, 5, 6}, N=6, K=10Output: 8Expla
6 min read