Sweaty Imposter

Single Number

EasyBitwise XORBlind 75JuniorOpen on LeetCodeUpdated

You're given a non-empty integer array nums in which every value appears exactly twice, except for one value that appears only once. Return that single value. Your solution must run in O(n) time and use only O(1) extra space, so you can't keep a table of counts or build a sorted copy. Values may be negative.

Examples

nums = [2,2,1] returns 1

2 appears twice and 1 appears once, so the single value is 1.

nums = [4,1,2,1,2] returns 4

1 and 2 each appear twice, even though their copies aren't next to each other. 4 is the only value without a partner.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • Every element appears twice except one.

Hints

Hint 1

Is there an operation that cancels equal pairs out and leaves the loner intact?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

XOR every element into a running result that starts at 0. XOR is commutative and associative, x ^ x = 0 and x ^ 0 = x, so the two copies of each paired value cancel wherever they sit in the array, and only the unpaired value survives. One pass, O(n) time, O(1) space.

Time

O(n)

Space

O(1)

Pitfall

Reaching for a set or a counter gives the right answer but uses O(n) space, which the problem rules out. Also seed the result with 0, the XOR identity: seeding it with nums[0] and then folding in all of nums cancels that element out.

Solutions

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int num : nums) result ^= num;
        return result;
    }
}
Drill This