Coding Interview PatternsSingle Number III
MediumBitwise Manipulation

Single Number III

Explanation & Solution

Description

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.

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

Input:nums = [1,2,1,3,2,5]
0
1
1
2
2
1
3
3
4
2
5
5
Output:[3,5]
0
3
1
5

Explanation: [5,3] is also a valid answer.

Constraints

  • 2 <= nums.length <= 3 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • Each integer in nums will appear twice, only two integers will appear once.

Approach

Bitwise Manipulation pattern

Key Insight

  • By finding a bit where the two unique numbers differ, we can partition the array into two groups and apply the Single Number I trick to each group
  • Time: O(n) | Space: O(1)

Visualization

Input:
[1, 2, 1, 3, 2, 5]
102112332455

No animation available

Left (L)Right (R)ConvergedDone
0 steps

Solution Code