Single Number

XOR-fold the whole array — pairs cancel, the lone unmatched value remains.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
bit-manipulation xor

Problem#

Every element appears twice except for one. Find the singleton in linear time and constant space.

Examples#

  • [2,2,1]1.
  • [4,1,2,1,2]4; [1]1.

Constraints#

  • 1 <= nums.length <= 3 * 10^4, fits in 32-bit int.

Approach#

XOR every element together. Because x ^ x = 0 and x ^ 0 = x, all paired values cancel, leaving the singleton.

Solution#

Single Number
class Solution {
public:
int singleNumber(vector<int>& nums) {
int x = 0;
for (int v : nums) x ^= v;
return x;
}
};

Editorial#

XOR is commutative and associative, so order doesn’t matter — the unique element falls out regardless of input order. This is the canonical example of using XOR’s self-inverse property to achieve O(1) space.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.