Sponsored
Sponsored
This approach involves directly computing the XOR for each range specified in the queries. For each query, iterate over the specified subarray range and compute the XOR.
Time Complexity: O(n * q), where n is the number of elements in the largest range and q is the number of queries.
Space Complexity: O(q) for storing the query results.
1import java.util.*;
2
3public class XorQueries {
4 public static int[] xorQueries(int[] arr, int[][] queries) {
5 int[] result = new int[queries.length];
6 for (int i = 0; i < queries.length; i++) {
7 int xor_result = 0;
8 for (int j = queries[i][0]; j <= queries[i][1]; j++) {
9 xor_result ^= arr[j];
10 }
11 result[i] = xor_result;
12 }
13 return result;
14 }
15
16 public static void main(String[] args) {
17 int[] arr = {1, 3, 4, 8};
18 int[][] queries = {{0, 1}, {1, 2}, {0, 3}, {3, 3}};
19 int[] result = xorQueries(arr, queries);
20 System.out.println(Arrays.toString(result));
21 }
22}
In this Java implementation, we iterate over each query, then use a nested loop to compute the XOR for the specified range. The results are stored in an array and printed using Arrays.toString()
.
To optimize the XOR computation, we can use a prefix XOR array. Compute the XOR of all elements up to each position in the array. Then to find the XOR for a range simply subtract the prefix value before the start of the range from the prefix at the end of the range.
Time Complexity: O(n + q), where n is the number of elements and q is the number of queries.
Space Complexity: O(n) for the prefix XOR array.
1
This C implementation computes the prefix XOR array, which is then used to quickly compute the XOR for any subrange as the difference between the prefix XOR at right + 1 and left indices.