Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmQueries to find the maximum Xor value between X and the nodes...

Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree

Given a perfect binary tree of N nodes, with nodes having values from 1 to N as depicted in the image below and Q queries where every query consists of two integers L and X. The task is to find the maximum possible value of X XOR Y where Y can be any node at level L
 

Examples: 

Input: Q[] = {{2, 5}, {3, 15}} 
Output: 

11 
1st Query: Level 2 has numbers 2 and 3. 
Therefore, 2^5 = 7 and 3^5 = 6. 
Hence, the answer is 7. 
2nd Query: Level 3 has numbers 4, 5, 6 and 7 
and 4^15 = 11 is the maximum possible.

Input: Q[] = {{ 1, 15 }, { 5, 23 }} 
Output: 
14 
15 
 

Approach: The numbers in level L contains L bits, e.g, in level 2 the numbers are 2 and 3 which can be represented using 2 bits in binary. Similarly, in level 3 the numbers are 4, 5, 6 and 7 can be represented with 3 bits. 
So we have to find an L bit number which gives maximum xor with X. Store the bits of X in an array a[]. Now, fill an array b[] of size L with elements opposite to that in a[], i.e., if a[i] is equal to 0 then put b[i] equal to 1 and vice-versa. 
Note that the L-1 index of b[]must always be 1. If size of a[] is less than b[] then fill the remaining indexes of b[] with 1. The array b[] is filled opposite to that of array a[] so that the number made from the bits of array b[] gives maximum xor value. Lastly, calculate the number made from b[] and return its xor with X as the answer to the query.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAXN 60
 
// Function to solve queries of the maximum xor value
// between the nodes in a given level L of a
// perfect binary tree and a given value X
int solveQuery(int L, int X)
{
    // Initialize result
    int res;
 
    // Initialize array to store bits
    int a[MAXN], b[L];
 
    // Initialize a copy of X
    // and size of array
    int ref = X, size_a = 0;
 
    // Storing the bits of X
    // in the array a[]
    while (ref > 0) {
        a[size_a] = ref % 2;
        ref /= 2;
        size_a++;
    }
 
    // Filling the array b[]
    for (int i = 0; i < min(size_a, L); i++) {
        if (a[i] == 1)
            b[i] = 0;
        else
            b[i] = 1;
    }
 
    for (int i = min(size_a, L); i < L; i++)
        b[i] = 1;
 
    b[L - 1] = 1;
 
    // Initializing variable which gives
    // maximum xor
    int temp = 0, p = 1;
 
    for (int i = 0; i < L; i++) {
        temp += b[i] * p;
        p *= 2;
    }
 
    // Getting the maximum xor value
    res = temp ^ X;
 
    // Return the result
    return res;
}
 
// Driver code
int main()
{
    int queries[][2] = { { 2, 5 }, { 3, 15 } };
    int q = sizeof(queries) / sizeof(queries[0]);
 
    // Perform queries
    for (int i = 0; i < q; i++)
        cout << solveQuery(queries[i][0],
                           queries[i][1])
             << endl;
 
    return 0;
}


Java




// Java implementation of the approach
 
class GFG
{
     
    static int MAXN = 60;
     
    // Function to solve queries of the maximum xor value
    // between the nodes in a given level L of a
    // perfect binary tree and a given value X
    static int solveQuery(int L, int X)
    {
        // Initialize result
        int res;
     
        // Initialize array to store bits
        int []a = new int [MAXN];
        int []b = new int[L];
     
        // Initialize a copy of X
        // and size of array
        int refer = X, size_a = 0;
     
        // Storing the bits of X
        // in the array a[]
        while (refer > 0)
        {
            a[size_a] = refer % 2;
            refer /= 2;
            size_a++;
        }
     
        // Filling the array b[]
        for (int i = 0; i < Math.min(size_a, L); i++)
        {
            if (a[i] == 1)
                b[i] = 0;
            else
                b[i] = 1;
        }
     
        for (int i = Math.min(size_a, L); i < L; i++)
            b[i] = 1;
     
        b[L - 1] = 1;
     
        // Initializing variable which gives
        // maximum xor
        int temp = 0, p = 1;
     
        for (int i = 0; i < L; i++)
        {
            temp += b[i] * p;
            p *= 2;
        }
     
        // Getting the maximum xor value
        res = temp ^ X;
     
        // Return the result
        return res;
    }
     
    // Driver code
    static public void main (String args[])
    {
        int [][]queries= { { 2, 5 }, { 3, 15 } };
        int q = queries.length;
     
        // Perform queries
        for (int i = 0; i < q; i++)
            System.out.println( solveQuery(queries[i][0],
                            queries[i][1]) );
         
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the approach
 
MAXN = 60
 
# Function to solve queries of the maximum xor value
# between the nodes in a given level L of a
# perfect binary tree and a given value X
def solveQuery(L, X):
     
    # Initialize result
    res = 0
 
    # Initialize array to store bits
    a = [0 for i in range(MAXN)]
    b = [0 for i in range(MAXN)]
 
    # Initialize a copy of X
    # and size of array
    ref = X
    size_a = 0
 
    # Storing the bits of X
    # in the array a[]
    while (ref > 0):
        a[size_a] = ref % 2
        ref //= 2
        size_a+=1
 
    # Filling the array b[]
    for i in range(min(size_a,L)):
        if (a[i] == 1):
            b[i] = 0
        else:
            b[i] = 1
 
 
    for i in range(min(size_a, L),L):
        b[i] = 1
 
    b[L - 1] = 1
 
    # Initializing variable which gives
    # maximum xor
    temp = 0
    p = 1
 
    for i in range(L):
        temp += b[i] * p
        p *= 2
 
    # Getting the maximum xor value
    res = temp ^ X
 
    # Return the result
    return res
 
# Driver code
queries= [ [ 2, 5 ], [ 3, 15 ] ]
 
q = len(queries)
 
# Perform queries
for i in range(q):
    print(solveQuery(queries[i][0],queries[i][1]))
 
# This code is contributed by mohit kumar 29


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    static int MAXN = 60;
     
    // Function to solve queries of the maximum xor value
    // between the nodes in a given level L of a
    // perfect binary tree and a given value X
    static int solveQuery(int L, int X)
    {
        // Initialize result
        int res;
     
        // Initialize array to store bits
        int []a = new int [MAXN];
        int []b = new int[L];
     
        // Initialize a copy of X
        // and size of array
        int refer = X, size_a = 0;
     
        // Storing the bits of X
        // in the array a[]
        while (refer > 0)
        {
            a[size_a] = refer % 2;
            refer /= 2;
            size_a++;
        }
     
        // Filling the array b[]
        for (int i = 0; i < Math.Min(size_a, L); i++)
        {
            if (a[i] == 1)
                b[i] = 0;
            else
                b[i] = 1;
        }
     
        for (int i = Math.Min(size_a, L); i < L; i++)
            b[i] = 1;
     
        b[L - 1] = 1;
     
        // Initializing variable which gives
        // maximum xor
        int temp = 0, p = 1;
     
        for (int i = 0; i < L; i++)
        {
            temp += b[i] * p;
            p *= 2;
        }
     
        // Getting the maximum xor value
        res = temp ^ X;
     
        // Return the result
        return res;
    }
     
    // Driver code
    static public void Main ()
    {
        int [,]queries= { { 2, 5 }, { 3, 15 } };
        int q = queries.Length;
     
        // Perform queries
        for (int i = 0; i < q; i++)
            Console.WriteLine( solveQuery(queries[i,0],
                            queries[i,1]) );
         
    }
}
 
// This code is contributed by anuj_67..


Javascript




<script>
 
// Javascript implementation of the approach
var MAXN = 60;
 
// Function to solve queries of the maximum
// xor value between the nodes in a given
// level L of a perfect binary tree and a
// given value X
function solveQuery(L, X)
{
     
    // Initialize result
    var res;
 
    // Initialize array to store bits
    var a = Array(MAXN), b = Array(L);
 
    // Initialize a copy of X
    // and size of array
    var ref = X, size_a = 0;
 
    // Storing the bits of X
    // in the array a[]
    while (ref > 0)
    {
        a[size_a] = ref % 2;
        ref = parseInt(ref / 2);
        size_a++;
    }
 
    // Filling the array b[]
    for(var i = 0; i < Math.min(size_a, L); i++)
    {
        if (a[i] == 1)
            b[i] = 0;
        else
            b[i] = 1;
    }
 
    for(var i = Math.min(size_a, L); i < L; i++)
        b[i] = 1;
 
    b[L - 1] = 1;
 
    // Initializing variable which gives
    // maximum xor
    var temp = 0, p = 1;
 
    for(var i = 0; i < L; i++)
    {
        temp += b[i] * p;
        p *= 2;
    }
 
    // Getting the maximum xor value
    res = temp ^ X;
 
    // Return the result
    return res;
}
 
// Driver code
var queries = [ [ 2, 5 ], [ 3, 15 ] ];
var q = queries.length;
 
// Perform queries
for(var i = 0; i < q; i++)
    document.write(solveQuery(queries[i][0],
                              queries[i][1]) + "<br>");
                               
// This code is contributed by rutvik_56
 
</script>


Output: 

7
11

 

Time Complexity: O(q * MAXN)
Auxiliary Space:  O(MAXN)

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 neveropen!

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments