PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: rahularya1
Tester: iceknight1093
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
None
PROBLEM:
Given an array A, you’re allowed to remove at most one element from it.
Find the minimum possible value of the XOR of the remaining elements.
EXPLANATION:
The simplest way to solve this problem is to utilize two properties of XOR:
- XOR is an involution, which is a fancy way of saying x\oplus x = 0 for all x.
- XOR is associative and commutative, meaning you can move integers around in an expression and their XOR doesn’t change.
One way to use these properties is, if you have the XOR of several integers and want to remove one of them, you can do that by just XOR-ing with that integer!
For example, if we have the N integers [A_1, A_2, \ldots, A_N] and we want to find the XOR of everything except A_i, we can do it as:
Notice that the left part of that expression is just the XOR of all the elements of A!
So, to compute the XOR of everything other than A_i, we:
- First compute S = A_1\oplus A_2\oplus \ldots \oplus A_N.
- Then compute S\oplus A_i.
Now it’s easy to see that we can do this quickly for each A_i, since S is a constant and so only needs to be computed once.
The final answer is the minimum of S (to account for the case when no elements are removed), and the minimum value among all the (S\oplus A_i) values.
TIME COMPLEXITY
\mathcal{O}(N) per testcase.
CODE:
Editorialist's code (Python)
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
allxor = 0
for x in a: allxor ^= x
ans = allxor
for x in a: ans = min(ans, allxor ^ x)
print(ans)