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 - XOR Bit Manipulation INPUT nums array: 1 2 1 3 2 5 [0] [1] [2] [3] [4] [5] Elements appearing twice: 1, 1 2, 2 Elements appearing once: 3 5 Constraints: - O(n) time complexity - O(1) space complexity - Exactly 2 unique numbers ALGORITHM STEPS 1 XOR All Elements xor = 1^2^1^3^2^5 = 3^5 = 6 binary: 110 (3^5) 2 Find Rightmost Set Bit diff = xor and (-xor) = 2 bit mask: 010 3 Partition by Bit Group by (num and diff) Bit=0: 1,1,5 1^1^5 = 5 Bit=1: 2,2,3 2^2^3 = 3 4 XOR Each Group Pairs cancel, singles remain x = 5 y = 3 Time: O(n) | Space: O(1) FINAL RESULT Two unique numbers found: 3 5 Output Array: [3, 5] Verification: 3 appears once - OK 5 appears once - OK 1,2 appear twice - OK O(n) time, O(1) space - OK SUCCESS! Key Insight: XOR of all numbers gives (a XOR b) where a,b are the unique numbers. The rightmost set bit in this result indicates a position where a and b differ. Using this bit as a mask, we can partition all numbers into two groups - each containing exactly one unique number. XOR within each group reveals the answer! TutorialsPoint - Single Number III | Optimal XOR Bit Manipulation Solution
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