medium

Range XOR Queries with Updates

An integer array receives a stream of two kinds of queries: set position i to value v, or report the bitwise XOR of all elements from l to r inclusive. Answer every query efficiently.

Constraints
  • 1 ≤ n, q ≤ 2 · 10^5
  • 0 ≤ a[i], v < 2^30
  • 0 ≤ l ≤ r < n
Examples
in: a = [1,3,4,8]; xor(1,3), update(2,6), xor(0,2)
out: 15, 4
Recognition clues
  • XOR is associative and invertible — a range can be combined from pieces
  • Updates interleaved with range queries
  • Same shape as range sum with a different combine operator
Pattern
Segment / Fenwick Tree

Prefix sums break the moment the array changes, since every prefix after the update shifts. A Fenwick or segment tree stores partial aggregates over power-of-two ranges so both a point update and a range query touch only O(log n) nodes. Use a sparse table instead when the array is static and the operation is idempotent (min, max, gcd).

Solution

Use a segment tree whose nodes store the XOR of their range; XOR is associative, so any node value is the XOR of its two children. Updates rewrite a leaf and recompute ancestors; queries combine O(log n) disjoint nodes covering [l, r]. Because XOR is its own inverse, a Fenwick tree over prefix XORs also works: answer [l, r] as prefix(r) ⊕ prefix(l - 1).

time O(log n) per operationspace O(n)
Alternative approaches
  • Without updates, a prefix-XOR array answers queries in O(1). Sqrt decomposition trades to O(√n) per operation with trivial code.
Code it yourself
Solve in
Hints:
Learn Segment Tree▶ Visualize