XOR Queries of a Subarray - Prefix XOR [JS]

Description 

Solution: Prefix XOR

XORing a number with itself cancels itself out.
i.e: a = a ^ b ^ b

Store the prefix XOR and use pXor[j + 1] ^ pXor[i] to get the range XOR of numbers between indices i and j.

n = length of arrm = number of queries
Time Complexity: O(n + m)
Space Complexity: O(n) excluding output

function xorQueries(arr, queries) {
  let n = arr.length, pXor = Array(n + 1).fill(0);
  for (let i = 1; i <= n; i++) {
    pXor[i] = pXor[i - 1] ^ arr[i - 1];
  }
  let answer = [];
  for (let [left, right] of queries) {
    answer.push(pXor[right + 1] ^ pXor[left]);
  }
  return answer;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]