2026/10/31 1:43:38

LeetCode //C - 1310. XOR Queries of a Subarray

LeetCode //C - 1310. XOR Queries of a Subarray 1310. XOR Queries of a SubarrayYou 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_ilefti​tor 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 00013 00114 01008 1000The 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] 8Example 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^41arr.length,queries.length3∗1041 a r r [ i ] 10 9 1 arr[i] 10^91arr[i]109queries[i].length 20 lefti righti arr.lengthFrom: LeetCodeLink: 1310. XOR Queries of a SubarraySolution: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:#includestdlib.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((arrSize1)*sizeof(int));int*answer(int*)malloc(queriesSize*sizeof(int));prefix[0]0;for(inti0;iarrSize;i){prefix[i1]prefix[i]^arr[i];}for(inti0;iqueriesSize;i){intleftqueries[i][0];intrightqueries[i][1];answer[i]prefix[right1]^prefix[left];}free(prefix);*returnSizequeriesSize;returnanswer;}