CSES - Range Xor Queries
Authors: Danh Ta Chi Thanh, Nathan Gong
Explanation
Whenever we come across range queries, prefix sums should immediately come to mind. However, since we are dealing with XOR sums over a range, we have to use a prefix XOR array rather than a prefix sum array. To do so, we can define as an array such that . Thus, for each query , our answer is simply .
Proof
We know that . We also know that .
Therefore, since for any :
.
This simplifies to , which is exactly what we're looking for.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int MAX_N = 2e5;int n, q, arr[MAX_N + 1], prefix[MAX_N + 1], a, b;int main() {ios_base::sync_with_stdio(false);cin.tie(0);
Java
import java.io.*;import java.util.*;public class RangeXorQueries {public static void main(String[] args) {Kattio io = new Kattio();int n = io.nextInt();int q = io.nextInt();// arr and prefix use 1-based indexing
Python
n, q = map(int, input().split())arr = list(map(int, input().split()))xor_arr = [0] * (n + 1)for i in range(1, n + 1):xor_arr[i] = arr[i - 1] ^ xor_arr[i - 1]for _ in range(q):a, b = map(int, input().split())print(xor_arr[b] ^ xor_arr[a - 1])
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!