1310. XOR Queries of a Subarray
You are given an array arr of positive integers. You are also given the array queries whereq u e r i e s [ i ] = [ l e f t i , r i g h t i ] queries[i] = [left_i, right_i]queries[i]=[lefti,righti].
For each query i compute the XOR of elements froml e f t i left_ileftitor i g h t i right_irighti(that is,a r r [ l e f t i ] arr[left_i]arr[lefti]XORa r r [ l e f t i + 1 ] arr[left_i + 1]arr[lefti+1]XOR … XORa r r [ r i g h t i ] arr[right_i]arr[righti]).
Return an array answer where answer[i] is the answer to thei t h i^{th}ithquery.
Example 1:
Input:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output:[2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8
Example 2:
Input:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output:[8,0,4,4]
Constraints:
- 1 < = a r r . l e n g t h , q u e r i e s . l e n g t h < = 3 ∗ 10 4 1 <= arr.length, queries.length <= 3 * 10^41<=arr.length,queries.length<=3∗104
- 1 < = a r r [ i ] < = 10 9 1 <= arr[i] <= 10^91<=arr[i]<=109
- queries[i].length == 2
- 0 <= lefti <= righti < arr.length
From: LeetCode
Link: 1310. XOR Queries of a Subarray
Solution:
Ideas:
Build a prefix XOR array:
prefix[i] = arr[0] XOR arr[1] XOR … XOR arr[i - 1]
Then the XOR from left to right is:
prefix[right + 1] XOR prefix[left]
The elements before left appear twice and cancel because x XOR x = 0.
Code:
#include<stdlib.h>/** * Note: The returned array must be malloced, assume caller calls free(). */int*xorQueries(int*arr,intarrSize,int**queries,intqueriesSize,int*queriesColSize,int*returnSize){(void)queriesColSize;int*prefix=(int*)malloc((arrSize+1)*sizeof(int));int*answer=(int*)malloc(queriesSize*sizeof(int));prefix[0]=0;for(inti=0;i<arrSize;i++){prefix[i+1]=prefix[i]^arr[i];}for(inti=0;i<queriesSize;i++){intleft=queries[i][0];intright=queries[i][1];answer[i]=prefix[right+1]^prefix[left];}free(prefix);*returnSize=queriesSize;returnanswer;}