← DSA
EASY

Single Number

PracticeNeetCode ↗LeetCode ↗

Given a non-empty array of integers nums where every element appears exactly twice except for one, find that single element — in linear time, without extra space beyond a constant.

Example

Input nums = [4,1,2,1,2]
Output 4

Key Pointers

Step-by-Step Analysis

  1. Initialize result = 0.
  2. For each number n in nums, update result ^= n.
  3. Every value that appears twice XORs itself away by the end.
  4. Return result — the one value left unpaired.

Complexity

Time: O(n) — Space: O(1)

Code

def singleNumber(nums: list[int]) -> int:
    result = 0
    for n in nums:
        result ^= n
    return result

Code Explanation

How the solution above works, piece by piece.

  1. XOR has two useful rules: x ^ x = 0 and x ^ 0 = x. It's also order-independent.
  2. XOR-ing every number means each pair cancels out, whatever order they appear in.
  3. What remains is the number without a partner.
  4. O(n) time and O(1) space; no hash set needed.

Visual Walkthrough

Running it on nums = [4, 1, 2, 1, 2]:

trace100^ 4result = 4101^ 1result = 5111^ 2result = 7110^ 1result = 6100^ 2result = 4
The result is shown in binary after each XOR. The two 1s cancel, the two 2s cancel, and 4 (100) is left.
1 bit

Video Explanation

NeetCode — Single Number, LeetCode 136