#1310
Medium Algorithms Xor queries of a subarray
Array Bit Manipulation Prefix Sum
78.1% acceptance
Feb 25, 2026
2094
60
You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].
For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).
Return an array answer where answer[i] is the answer to the ith query.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn xor_queries(arr: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> {
let n = arr.len();
let mut prefix = vec![0i32; n + 1];
for i in 0..n {
prefix[i + 1] = prefix[i] ^ arr[i];
}
queries.iter().map(|q| prefix[q[1] as usize + 1] ^ prefix[q[0] as usize]).collect()
}
}