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 - XOR Bit Manipulation INPUT nums = [2, 1, 2, 3, 1] 2 1 2 3 1 i=0 i=1 i=2 i=3 i=4 Appears twice Appears once Constraints: - O(n) time complexity - O(1) space complexity - All except one appear twice ALGORITHM STEPS 1 Initialize result = 0 result = 0 (binary: 000) 2 XOR each element result = result XOR nums[i] XOR Operations (^) 0 ^ 2 = 2 (000 ^ 010 = 010) 2 ^ 1 = 3 (010 ^ 001 = 011) 3 ^ 2 = 1 (011 ^ 010 = 001) 1 ^ 3 = 2 (001 ^ 011 = 010) 2 ^ 1 = 3 (010 ^ 001 = 011) 3 Return result Pairs cancel out (a^a=0) 4 Single remains Only unique num survives FINAL RESULT After XOR all elements: 3 Binary: 011 Output: 3 The single number OK - Verified! 2 appears: 2 times 1 appears: 2 times 3 appears: 1 time Time: O(n) | Space: O(1) Key Insight: XOR Properties 1. a XOR a = 0 (any number XORed with itself equals zero) 2. a XOR 0 = a (any number XORed with zero equals itself) 3. XOR is commutative and associative, so order doesn't matter. Pairs cancel out, leaving only the single number! TutorialsPoint - Single Number | Optimal XOR Solution
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