beginner · bit manipulation · XOR

The sock without a pair

Problem

Every value in a list appears exactly twice, except one value that appears once. Find it in O(n) time and O(1) extra space.

Constraints

  • 1 ≤ n ≤ 31, n odd
  • values from 0 to 999

Examples

[4, 1, 2, 1, 2] → 4

Show the solution

XOR everything

Pairs cancel under XOR regardless of order, leaving the single value.

Why it is correct

XOR is associative and commutative, so the XOR of the list equals (pairs XORed together) ^ single = 0 ^ single = single.

Complexity

Time O(n), extra space O(1). One XOR per value.

For contrast: Count occurrences with a hash map. That costs O(n) time and O(n) space.

Edge cases

  • One value.
  • The single value is 0.

Common mistakes

  • Summing with alternating signs (depends on order).
  • Assuming the pairs are adjacent.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class SingleNumber
{
    /// <summary>The one value that appears once when every other appears twice. O(n), O(1) space.</summary>
    public static int Find(int[] values)
    {
        int result = 0;
        foreach (int value in values)
            result ^= value; // x ^ x = 0, so pairs cancel in any order
        return result;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/SingleNumber.cs

from collections.abc import Iterable
 
 
def find(values: Iterable[int]) -> int:
    """The one value that appears once when every other appears twice. O(n), O(1) space."""
    result = 0
    for value in values:
        result ^= value  # x ^ x = 0, so pairs cancel in any order
    return result

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/single_number.py

package dev.bekadan.dsa.problems;
 
public final class SingleNumber {
    private SingleNumber() {
    }
 
    /** The one value that appears once when every other appears twice. O(n), O(1) space. */
    public static int find(int[] values) {
        int result = 0;
        for (int value : values) {
            result ^= value; // x ^ x = 0, so pairs cancel in any order
        }
        return result;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/SingleNumber.java

#pragma once
 
#include <span>
 
namespace bekadan::dsa::problems {
 
// The one value that appears once when every other appears twice. O(n), O(1) space.
inline int single_number(std::span<const int> values) {
    int result = 0;
    for (int value : values)
        result ^= value;  // x ^ x = 0, so pairs cancel in any order
    return result;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/single_number.hpp