Editorial for Range XOR
Use this editorial only when stuck, and do not copy-paste code from it.
Please be respectful to the problem author and editorialist. Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let prefi be the XOR of the first i elements:
- pref0=0
- prefi=a1⊕a2⊕⋯⊕ai
XOR is its own inverse, so:
prefr⊕prefl−1=(a1⊕⋯⊕al−1⊕al⊕⋯⊕ar)⊕(a1⊕⋯⊕al−1)=al⊕⋯⊕ar
So we first build the prefix XOR array in O(n), then answer each query in O(1).
The total time complexity is O(n+q).
Solution (Python)
import sys
n = int(input())
values = list(map(int, input().split()))
prefix = [0] * (n + 1)
for i, value in enumerate(values, start=1):
prefix[i] = prefix[i - 1] ^ value
q = int(input())
answers = []
for _ in range(q):
l, r = map(int, input().split())
answers.append(str(prefix[r] ^ prefix[l - 1]))
sys.stdout.write("\n".join(answers) + "\n")
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.