In an array where every element appears twice except one, find the single element (e.g. [4,1,2,1,2] -> 4).
XOR every element together: identical values cancel (x ^ x = 0) and XOR with 0 leaves the value (x ^ 0 = x), so the unpaired element remains. This is O(n) time and O(1) space, beating a frequency map or sorting.
public static int singleNumber(int[] a) {
int result = 0;
for (int x : a) result ^= x;
return result;
}function singleNumber(a) {
return a.reduce((acc, x) => acc ^ x, 0);
}def single_number(a):
result = 0
for x in a:
result ^= x
return resultThe XOR-cancel trick is a memorable constant-space technique that also solves missing-number and find-the-duplicate variants.
A candidate uses a HashMap of counts (O(n) space). What is the O(1)-space trick?