![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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)