Problem 83
Single Number
Easy · 10 pts · Array, Bit Manipulation
Problem
You are given an array of N integers in which every value appears exactly twice, except for one value that appears only once. Find that single value. A hash map of counts works, but there is an elegant trick with no extra memory: XOR all the elements together. Since x XOR x = 0 and x XOR 0 = x, every pair cancels out, and only the single value remains.
Input
First line: integer N (odd). Second line: N space-separated integers.
Output
Print the element that appears once.
Constraints
1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000
Example input
3 2 2 1
Example output
1
Explanation
In 2 2 1, the value 2 appears twice and 1 appears once, so the answer is 1. With XOR: 2 XOR 2 XOR 1 = 0 XOR 1 = 1.