Single Number

Pattern: XOR tricks

easy

XOR every value together. Each pair cancels to 0, and the value that appears once is all that is left.

The problem

Every value in a non-empty array appears exactly twice, except one value that appears once. Return that value, in O(n) time and O(1) extra memory. For example, [2, 2, 1] gives 1 and [4, 1, 2, 1, 2] gives 4.

The function name singleNumber matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • What is x ^ x? And x ^ 0?
  • Does the order of XOR operations matter?
  • What is left after XOR-ing everything?

Hints

    Brute force, and why it fails

    Count each value with a hash map: O(n) time but O(n) memory. Sorting then scanning: O(n log n). XOR uses O(1) memory.

    The key insight

    XOR is a "did this appear an odd number of times" detector, bit by bit, for the whole array at once.

    Dry run

    40 
    11 
    22 
    13 
    24 
    x0

    nums = [4, 1, 2, 1, 2]. Start with x = 0.

    Step 1 of 4

    The plan

    x = 0
    for v in nums: x = x ^ v
    return x
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with one variable.

    Edge cases

    • One element: itself.
    • Negative values: XOR works on their bits the same way.
    • The single value is 0: the result is 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int singleNumber(int[] nums) {
            int x = 0;
            for (int v : nums) x ^= v;              // pairs cancel (v ^ v = 0); the single value is left
            return x;
        }
    }

    C++

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int x = 0;
            for (int v : nums) x ^= v;              // pairs cancel (v ^ v = 0); the single value is left
            return x;
        }
    };

    Python

    class Solution:
        def singleNumber(self, nums: list[int]) -> int:
            x = 0
            for v in nums:
                x ^= v                              # pairs cancel (v ^ v = 0); the single value is left
            return x

    Common mistakes

    • Using a sum instead of XOR (pairs do not cancel in a sum).
    • Starting x at something other than 0.
    • Using this when values appear three times (see Single Number II).

    Similar problems