Single Number - Problem

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,2,3,1]
Output: 3
💡 Note: Numbers 2 and 1 each appear twice, while 3 appears only once. The single number is 3.
Example 2 — Single Element
$ Input: nums = [4,1,2,1,2]
Output: 4
💡 Note: Numbers 1 and 2 each appear twice, while 4 appears only once. The single number is 4.
Example 3 — Minimum Size
$ Input: nums = [1]
Output: 1
💡 Note: Array has only one element, so 1 is the single number that doesn't appear twice.

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • -3 × 104 ≤ nums[i] ≤ 3 × 104
  • Each element in the array appears twice except for one element which appears only once

Visualization

Tap to expand
Single Number Problem OverviewFind the element that appears once while all others appear twice21231Input: [2, 1, 2, 3, 1]PAIRPAIR3SINGLEOutput: 3
Understanding the Visualization
1
Input
Array where every element appears twice except one
2
Process
Use XOR to cancel out identical pairs
3
Output
The single number that doesn't have a pair
Key Takeaway
🎯 Key Insight: XOR all elements - identical pairs cancel out (a ⊕ a = 0), leaving only the single number
Asked in
Google 42 Amazon 38 Microsoft 31 Apple 28 Facebook 25
336.8K Views
High Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen