Single Number III

Given an integer array nums in which exactly two elements appear only once and every other element appears exactly twice, find the two elements that appear once. You can return the answer in any order. The algorithm must run in linear time and use only constant extra space.

30:00

Single Number III
medium
Free written solution
Topics
Companies

Given an integer array nums in which exactly two elements appear only once and every other element appears exactly twice, find the two elements that appear once. You can return the answer in any order. The algorithm must run in linear time and use only constant extra space.

Example 1:
Input: {"nums":[1,2,1,3,2,5]}
Output: [3,5]
Constraints:
  • 2≤nums.length≤3×1042 \leq \text{nums.length} \leq 3 \times 10^4

  • −231≤nums[i]≤231−1-2^{31} \leq \text{nums}[i] \leq 2^{31} - 1

  • Each integer in nums appears twice, except for two integers which appear once.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,1,3,2,5]}

XOR cancels pairs: x ^ x = 0. Folding all 6 numbers together leaves a ^ b, the XOR of the two singles.

nums in binary (4 bits)

1
0
0
0
1
2
0
0
1
0
1
0
0
0
1
3
0
0
1
1
2
0
0
1
0
5
0
1
0
1
xr
0
0
0
0

xr = a ^ b = 0

Variables
VariableValue
xr0
DepthFunction Call
Stack empty
0/15