awelgorithms

Prefix XOR as a range XOR

Updated

Inclusive XOR prefix: P[i] = a[0] ⊕ … ⊕ a[i], P[-1]=0. XOR is its own inverse, so [L, R] is P[R] ⊕ P[L-1]. No division, zeros are fine.

What to focus on

Same shape as range sum, operation ⊕. Check a one-cell range equals a[i].

Worked examples

build

a = [4, 1, 9]
  1. P[0] ← 4
  2. 4⊕1 = 5
  3. 5⊕9 = 12

Result: P = [4, 5, 12]

middle range

a = [4, 1, 9], [1, 2]
  1. P[2]⊕P[0] = 12⊕4 = 8
  2. check 1⊕9 = 8

Result: 8

whole and one

a = [4, 1, 9], [0, 2] and [0, 0]
  1. 12⊕0 = 12
  2. 4⊕0 = 4

Result: whole 12, cell 4

Try it

Write xorPrefix(a). a is the input array. Inclusive P[i] is a[0] ⊕ … ⊕ a[i]. Return P. [4, 1, 9] → P = [4, 5, 12] [1, 2] → 8 [0, 2] → 12 [0, 0] → 4

a is a non-empty array of integers. Inclusive XOR prefix. 0 ≤ L ≤ R < n. P[i] covers a[0..i].