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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int *xorQueries(int *arr, int arrSize, int **queries, int queriesSize, int *queriesColSize, int *returnSize) {
5 *returnSize = queriesSize;
6 int *result = (int *)malloc(sizeof(int) * queriesSize);
7
8 for (int i = 0; i < queriesSize; i++) {
9 int left = queries[i][0], right = queries[i][1];
10 int xor_result = 0;
11 for (int j = left; j <= right; j++) {
12 xor_result ^= arr[j];
13 }
14 result[i] = xor_result;
15 }
16 return result;
17}
18
19int main() {
20 int arr[] = {1, 3, 4, 8};
21 int arrSize = 4;
22 int queries[][2] = {{0, 1}, {1, 2}, {0, 3}, {3, 3}};
23 int queriesSize = 4;
24 int queriesColSize[] = {2, 2, 2, 2};
25 int *resultSize = (int *)malloc(sizeof(int));
26 int **queriesPointer = (int **)malloc(queriesSize * sizeof(int *));
27 for (int i = 0; i < queriesSize; i++) {
28 queriesPointer[i] = queries[i];
29 }
30 int *result = xorQueries(arr, arrSize, queriesPointer, queriesSize, queriesColSize, resultSize);
31 for (int i = 0; i < *resultSize; i++) {
32 printf("%d ", result[i]);
33 }
34 free(resultSize);
35 free(result);
36 free(queriesPointer);
37 return 0;
38}
This C implementation uses a nested loop for each query. The outer loop iterates through each query, and the inner loop computes the XOR from the left index to the right index of each query, storing the result in the output array.
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.