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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem