1310. XOR Queries of a Subarray

T: O(n+q)
S: O(n+q)
class Solution {
    public int[] xorQueries(int[] arr, int[][] queries) {
        int n = arr.length;
        int[] xorRes = new int[n];
        xorRes[0] = arr[0];
        for (int i = 1; i < n; i++) {
            xorRes[i] = (xorRes[i-1] ^ arr[i]);
        }

        int[] result = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int a = queries[i][0];
            int b = queries[i][1];
            if (a == b) {
                result[i] = arr[a];
            } else if (a == 0) {
                result[i] = xorRes[b];
            } else {
                result[i] = (xorRes[b] ^ xorRes[a-1]);
            }
        }
        return result;
    }
}

/**
sunarray xor

01 02

2
14
8421  
 001
 011
 010 = 2

 010 (2^4)
 100  
 110 = 6   (02)

 110 = 6
1000 = 8 -> 6^8
1110 = 14  
   
   03 = 04xor4


   02 ^ 00 = 6 ^ 1
   110
   001
   = 111 = 7

so in xor:
   [i, j] = [0, j] ^ [0, i-1]

and [0,0] means arr[0], [3,3] means arr[3]
and [0,3] just return xorRes[3]


T: O(n+q)
S: O(n+q)
 */

Last updated

Was this helpful?