Open In App

Nitika and her queries

Last Updated : 11 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Nitika recently read about XOR operation, and she got obsessed with it. She has an array a containing N Positive integers. She wants to perform Q queries on the array. In a query, she gives two integers L and R (1 based indexing). Now, she asks what is the xor of all the elements of the array after not including the subarray ranging from L to R (both inclusive). Nitika guarantees that in each query, The resulting array is not empty. The queries are given in a 2D matrix query having L and R for each entry.

Examples:

Input: N = 10, Q = 3, a[] = {4, 7, 8, 5, 9, 6, 1, 0, 20, 10}, query = {{3, 8},{1, 6},{2, 3}}
Output:
29
31
17
Explanation: For the first query: The resulting array is: (4 ,7 ,20, 10). Their Xor will be: 29.
For the Second query: The resulting array is: (1, 0, 20, 10). Their Xor will be: 31.
For the Third query: The resulting array is: (4, 5, 9, 6, 1,0 ,20, 10). Their Xor will be: 17.

Input: N = 8, Q = 3. a[] = {4, 7, 8, 5, 9, 6, 1, 0}, query[] = {{2, 4}, {1, 2}, {2, 3}}
Output:
10
3
15
Explanation: For the first query: The resulting array is: (4 ,9, 6, 1, 10). Their Xor will be: 10.
For the Second query: The resulting array is: (8, 5, 9, 6, 1, 0). Their Xor will be: 3.
For the Third query: The resulting array is: (4, 5, 9, 6, 1, 0). Their Xor will be: 15.

Approach: The problem can be solved using the following approach:

The idea is to use the concept of prefix XOR. Calculates the XOR of all elements in the array up to each index and stores it in an auxiliary array x. The XOR of any subarray can then be computed efficiently using the XOR property.

For each query, the XOR of the subarray [L, R] is computed by XORing the prefix XOR values of R and (L-1) if applicable. The result is then XORed with the XOR of the entire array to get the final answer. Our implementation would efficiently handles multiple queries using the precomputed XOR array.

Key Steps of intuition:

  • Compute the prefix XOR array x.
  • For each query [L, R], calculate the XOR of [L, R] using the prefix XOR array.
  • XOR the result with the XOR of the entire array to obtain the final answer for each query.

Steps to solve the problem:

  • Iterate through the array, calculating the XOR of elements up to each index and store it in the x[] array.
  • Query Processing:
    • For each query, compute the XOR of the subarray [L, R] using the prefix XOR values.
    • XOR the result with the XOR of the entire array.
    • Append the final result to the answer vector.
  • Return the vector containing the XOR results for all queries.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <vector>
 
using namespace std;
 
// Function to calculate XOR of elements in a subarray
// after excluding another subarray
vector<int> specialXor(int N, int Q, int a[],
                       vector<int> query[])
{
    // code here
    vector<int> x(N, 0), ans;
 
    // Calculate prefix XOR array
    x[0] = a[0];
    for (int i = 1; i < N; i++) {
        x[i] = a[i] ^ x[i - 1];
    }
 
    int sep_xor = 0;
    for (int i = 0; i < Q; i++) {
        int l = query[i][0] - 1, r = query[i][1] - 1;
 
        // Calculate XOR of [L, R] using prefix XOR values
        if (l == 0)
            sep_xor = x[r];
        else
            sep_xor = x[r] ^ x[l - 1];
 
        // XOR with the XOR of the entire array to get the
        // final result
        ans.push_back(x[N - 1] ^ sep_xor);
    }
 
    return ans;
}
int main()
{
    // Input parameters
    int N = 10, Q = 3;
    int a[] = { 4, 7, 8, 5, 9, 6, 1, 0, 20, 10 };
    vector<int> query[] = { { 3, 8 }, { 1, 6 }, { 2, 3 } };
 
    // Call the specialXor function
    vector<int> result = specialXor(N, Q, a, query);
 
    // Print the results
    cout << "Results: ";
    for (int res : result) {
        cout << res << " ";
    }
    cout << endl;
 
    return 0;
}


Java




import java.util.*;
 
class Solution {
    // Function to calculate XOR of elements in a subarray
    // after excluding another subarray
    static List<Integer> specialXor(int N, int Q, int[] a,
                                    int[][] query)
    {
        // code here
        List<Integer> x = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
 
        // Calculate prefix XOR array
        x.add(a[0]);
        for (int i = 1; i < N; i++) {
            x.add(a[i] ^ x.get(i - 1));
        }
 
        int sep_xor = 0;
        for (int i = 0; i < Q; i++) {
            int l = query[i][0] - 1, r = query[i][1] - 1;
 
            // Calculate XOR of [L, R] using prefix XOR
            // values
            if (l == 0)
                sep_xor = x.get(r);
            else
                sep_xor = x.get(r) ^ x.get(l - 1);
 
            // XOR with the XOR of the entire array to get
            // the final result
            ans.add(x.get(N - 1) ^ sep_xor);
        }
 
        return ans;
    }
 
    public static void main(String[] args)
    {
        // Input parameters
        int N = 10, Q = 3;
        int[] a = { 4, 7, 8, 5, 9, 6, 1, 0, 20, 10 };
        int[][] query = { { 3, 8 }, { 1, 6 }, { 2, 3 } };
 
        // Call the specialXor function
        List<Integer> result = specialXor(N, Q, a, query);
 
        // Print the results
        System.out.print("Results: ");
        for (int res : result) {
            System.out.print(res + " ");
        }
        System.out.println();
    }
}


Python3




# Python Implementation
 
def special_xor(N, Q, a, queries):
    # Calculate prefix XOR array
    x = [0] * N
    x[0] = a[0]
    for i in range(1, N):
        x[i] = a[i] ^ x[i - 1]
 
    ans = []
 
    sep_xor = 0
    for i in range(Q):
        l, r = queries[i][0] - 1, queries[i][1] - 1
 
        # Calculate XOR of [L, R] using prefix XOR values
        if l == 0:
            sep_xor = x[r]
        else:
            sep_xor = x[r] ^ x[l - 1]
 
        # XOR with the XOR of the entire array to get the
        # final result
        ans.append(x[N - 1] ^ sep_xor)
 
    return ans
 
# Input parameters
N, Q = 10, 3
a = [4, 7, 8, 5, 9, 6, 1, 0, 20, 10]
queries = [(3, 8), (1, 6), (2, 3)]
 
# Call the special_xor function
result = special_xor(N, Q, a, queries)
 
# Print the results
print("Results:", *result)
 
 
 # This code is contributed by Tapesh(tapeshdua420)


C#




using System;
using System.Collections.Generic;
 
class Solution {
    // Function to calculate XOR of elements in a subarray
    // after excluding another subarray
    static List<int> SpecialXor(int N, int Q, int[] a,
                                int[][] query)
    {
        // code here
        List<int> x = new List<int>();
        List<int> ans = new List<int>();
 
        // Calculate prefix XOR array
        x.Add(a[0]);
        for (int i = 1; i < N; i++) {
            x.Add(a[i] ^ x[i - 1]);
        }
 
        int sep_xor = 0;
        for (int i = 0; i < Q; i++) {
            int l = query[i][0] - 1, r = query[i][1] - 1;
 
            // Calculate XOR of [L, R] using prefix XOR
            // values
            if (l == 0)
                sep_xor = x[r];
            else
                sep_xor = x[r] ^ x[l - 1];
 
            // XOR with the XOR of the entire array to get
            // the final result
            ans.Add(x[N - 1] ^ sep_xor);
        }
 
        return ans;
    }
 
    public static void Main(string[] args)
    {
        // Input parameters
        int N = 10, Q = 3;
        int[] a = { 4, 7, 8, 5, 9, 6, 1, 0, 20, 10 };
        int[][] query = new int[][] { new int[] { 3, 8 },
                                      new int[] { 1, 6 },
                                      new int[] { 2, 3 } };
 
        // Call the SpecialXor function
        List<int> result = SpecialXor(N, Q, a, query);
 
        // Print the results
        Console.Write("Results: ");
        foreach(int res in result)
        {
            Console.Write(res + " ");
        }
        Console.WriteLine();
    }
}


Javascript




function specialXOR(N, Q, a, queries) {
    // Calculate prefix XOR array
    const x = new Array(N);
    x[0] = a[0];
    for (let i = 1; i < N; i++) {
        x[i] = a[i] ^ x[i - 1];
    }
 
    const ans = [];
 
    let sepXOR = 0;
    for (let i = 0; i < Q; i++) {
        const l = queries[i][0] - 1;
        const r = queries[i][1] - 1;
 
        // Calculate XOR of [L, R] using prefix XOR values
        if (l === 0) {
            sepXOR = x[r];
        } else {
            sepXOR = x[r] ^ x[l - 1];
        }
 
        // XOR with the XOR of the entire array to get the final result
        ans.push(x[N - 1] ^ sepXOR);
    }
 
    return ans;
}
 
// Input parameters
const N = 10;
const Q = 3;
const a = [4, 7, 8, 5, 9, 6, 1, 0, 20, 10];
const queries = [
    [3, 8],
    [1, 6],
    [2, 3]
];
 
// Call the specialXOR function
const result = specialXOR(N, Q, a, queries);
 
// Print the results
console.log("Results:", ...result);


Output

Results: 29 31 17 









Time Complexity: O(N + Q), where N is the array size and Q is the number of queries.
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads