Single Number (XOR)

medium Math and Number Theory

Problem

In an array every number appears exactly twice, except one number that appears once. Read n (odd) and the array, and print the number that appears once. Use O(1) extra memory.

Constraints

  • 1 <= n <= 10^5, n is odd
  • -2^31 <= a[i] < 2^31

Examples

Input

5
4 1 2 1 2

Output

4

Solutions

Best approachTime O(n)Space O(1)

XOR is commutative. Each pair x ^ x becomes 0, and 0 ^ single = single. No hash set is needed, so the extra memory is O(1).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find the number that appears once.
 * Input   : n, then n integers.
 * Output  : The single number.
 * Approach: XOR cancels equal numbers.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a) {
        // Step 1: x ^ x = 0 and x ^ 0 = x. So equal numbers cancel each other.
        int result = 0;

        // Step 2: XOR all numbers. The pairs cancel, and only the single number stays.
        for (int value : a) {
            result = result ^ value;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. What is x ^ x?