1310. XOR Queries of a Subarray #534
-
Topics: You are given an array For each query Return an array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can make use of the prefix XOR technique. Here's how it works: Approach:
Plan:
Let's implement this solution in PHP: 1310. XOR Queries of a Subarray <?php
function xorQueries($arr, $queries) {
$n = count($arr);
$prefix = array_fill(0, $n, 0);
$prefix[0] = $arr[0];
// Build the prefix XOR array
for ($i = 1; $i < $n; $i++) {
$prefix[$i] = $prefix[$i - 1] ^ $arr[$i];
}
$result = [];
// Process each query
foreach ($queries as $query) {
list($left, $right) = $query;
if ($left == 0) {
$result[] = $prefix[$right];
} else {
$result[] = $prefix[$right] ^ $prefix[$left - 1];
}
}
return $result;
}
// Example 1
$arr1 = [1, 3, 4, 8];
$queries1 = [[0, 1], [1, 2], [0, 3], [3, 3]];
print_r(xorQueries($arr1, $queries1)); // Output: [2, 7, 14, 8]
// Example 2
$arr2 = [4, 8, 2, 10];
$queries2 = [[2, 3], [1, 3], [0, 0], [0, 3]];
print_r(xorQueries($arr2, $queries2)); // Output: [8, 0, 4, 4]
?> Explanation:
Time Complexity:
This approach ensures we can handle up to 30,000 queries on an array of size up to 30,000 efficiently. |
Beta Was this translation helpful? Give feedback.
We can make use of the prefix XOR technique. Here's how it works:
Approach:
Prefix XOR Array: We compute a prefix XOR array where
prefix[i]
represents the XOR of all elements from the start of the array up to indexi
. This allows us to compute the XOR of any subarray in constant time.XOR of a subarray:
left
andright
:left > 0
, we can compute the XOR fromleft
toright
asprefix[right] ^ prefix[left - 1]
.left == 0
, then the result is simplyprefix[right]
.This allows us to answer each query in constant time after constructing the prefix XOR array.
Plan: