LeetCode ยท #136
Single Number Solution
Every element appears twice except one. Find the single element in O(n) time and O(1) space.
01
Section One ยท Problem
Problem Statement
Given a non-empty array where every element appears twice except one, find that single one. Must run in O(n) time and O(1) extra space.
Example
Input: nums = [4,1,2,1,2]
Output: 4
Constraints
โข 1 โค nums.length โค 3 ร 10โด โข Each element appears twice except one
02
Section Two ยท Approach 1
HashMap โ O(n) time, O(n) space
Count frequencies. Return the element with count 1.
Problem: O(n) space. XOR gives O(1) space because
a โ a = 0 and a โ 0 = a. All duplicates cancel out, leaving only the single number.Java โ HashMap
import java.util.*;
class Solution {
public int singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for (int n : nums) map.merge(n, 1, Integer::sum);
for (var e : map.entrySet())
if (e.getValue() == 1) return e.getKey();
return -1;
}
}
Python โ Counter
from collections import Counter
class Solution:
def singleNumber(self, nums: list[int]) -> int:
return [k for k, v in Counter(nums).items() if v == 1][0]
03
Section Three ยท Approach 2
XOR โ O(n) time, O(1) space
XOR all elements. Since a โ a = 0 and a โ 0 = a, all duplicates cancel out, leaving only the single number.
๐ก Mental model: Imagine a light switch. Each number "flips" a switch. If a number appears twice, it flips on then off โ canceling out. After all flips, the only switch still on is the single number. XOR is that light switch โ same value twice returns to zero.
๐ฏ When to recognize this pattern: "Find the element that appears odd times when all others appear even times." XOR is the tool. Key properties: commutative, associative, self-inverse. Also used in LC 268 (Missing Number), LC 137 (Single Number II โ bit counting for triples), LC 260 (Single Number III โ two unique numbers).
04
Section Four ยท Trace
Visual Walkthrough
XOR โ Duplicates Cancel
05
Section Five ยท Implementation
Code โ Java & Python
Java โ XOR
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int n : nums) res ^= n;
return res;
}
}
Python โ XOR (reduce)
from functools import reduce
from operator import xor
class Solution:
def singleNumber(self, nums: list[int]) -> int:
return reduce(xor, nums)
06
Section Six ยท Analysis
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| HashMap | O(n) | O(n) |
| Sort + scan | O(n log n) | O(1) |
| XOR โ optimal | O(n) | O(1) |
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Single element | [42] | 0 โ 42 = 42. |
| Negative numbers | [-1,1,-1] | XOR works on negative ints (two's complement). |
| Zero is single | [0,1,1] | 0 is valid. XOR: 0โ1โ1 = 0. |
โ Common Mistake: Trying to solve with
sum(set) * 2 - sum(array). This works mathematically but can overflow for large values. XOR has no overflow risk and is the cleanest solution.