← Back to libraryQuestion 127 of 273
⌨️Java CodingBeginner

Single Number (Find the Unique Element)

📌 Definition:

In an array where every element appears twice except one, find the single element (e.g. [4,1,2,1,2] -> 4).

📖 Detailed Explanation:

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.

💻 Solutions:
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 result
🔑 Key Points:
  • x ^ x = 0, x ^ 0 = x — pairs cancel
  • XOR the whole array; the loner survives
  • O(n) time, O(1) space
  • No extra map or sort needed
🌍 Real-World Example:

The XOR-cancel trick is a memorable constant-space technique that also solves missing-number and find-the-duplicate variants.

🎯 Scenario-Based Interview Question:

A candidate uses a HashMap of counts (O(n) space). What is the O(1)-space trick?