Single Number III - Problem

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

You can return the answer in any order.

Constraints: You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,3,2,5]
Output: [3,5]
💡 Note: Numbers 1 and 2 each appear twice, while 3 and 5 each appear only once. Return the two unique numbers in any order.
Example 2 — Different Numbers
$ Input: nums = [-1,0]
Output: [-1,0]
💡 Note: Both numbers appear only once. This is the minimum case with exactly 2 elements.
Example 3 — Larger Array
$ Input: nums = [0,1,0,2,2,3]
Output: [1,3]
💡 Note: Numbers 0 and 2 appear twice each. Numbers 1 and 3 appear only once.

Constraints

  • 2 ≤ nums.length ≤ 3 × 104
  • -231 ≤ nums[i] ≤ 231 - 1
  • Each integer appears exactly twice except for two integers that appear only once

Visualization

Tap to expand
Single Number III: Find Two Unique NumbersInput: [1,2,1,3,2,5]121325appears twiceappears twiceduplicateonce only!duplicateonce only!XOR Approach1. XOR all → 3⊕52. Find diff bit3. Split & XOR groupsAlgorithm magically separates the two unique numbers35Output: [3, 5]
Understanding the Visualization
1
Input Analysis
Array with exactly two numbers appearing once, others twice
2
XOR Magic
Use XOR properties to mathematically separate the unique numbers
3
Result
Return the two unique numbers in any order
Key Takeaway
🎯 Key Insight: XOR has the perfect property that a⊕a=0, so duplicates cancel out, leaving us with just the XOR of our two unique numbers.
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 6
180.0K Views
Medium Frequency
~15 min Avg. Time
3.2K 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