Back to Practice
#0248
Single Number with XOR
EasyDSA18 min10 XP
Problem
Given nums where exactly one value appears once and every other value appears twice, return the single value.
Why This Matters
This is the simplest useful XOR identity: duplicates cancel out without extra memory.
Function Signature
def single_number(nums):
Examples
Example 1
Inputnums = [4, 1, 2, 1, 2]
Output4
1 and 2 cancel themselves through XOR, leaving 4.
Constraints
- Return the exact requested value.
- Handle empty or small inputs when the prompt allows them.
- Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Middle duplicates
Input[4, 1, 2, 1, 2]
Expected4
Only 4 appears once.
Single element
Input[9]
Expected9
The only element is the answer.
Hidden Test Categories
negative numberssingle number at endlarge duplicate set