Single Number
Easy
ArrayBit ManipulationXOR
Problem
Given an integer array nums where every element appears twice except for one, find that one. O(n) time, O(1) space.
Example 1
Input: nums = [2,2,1]
Output: 1
Example 2
Input: nums = [4,1,2,1,2]
Output: 4
Example 3
Input: nums = [1]
Output: 1
Constraints
- 1 ≤ nums.length ≤ 3·10⁴
- −3·10⁴ ≤ nums[i] ≤ 3·10⁴
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
Python
class Solution:
def singleNumber(self, nums):
r = 0
for x in nums:
r ^= x
return r
Java
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Single Number interactively → ← All solutions