Single Number III Problem
Description
LeetCode Problem 260.
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 analgorithm that runs in linear runtime complexity and usesonly constant extra space.
Example 1:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
Example 2:
Input: nums = [-1,0]
Output: [-1,0]
Example 3:
Input: nums = [0,1]
Output: [1,0]
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.
Solution
Approach: XOR and Split by One Bit
XOR of a number with itself is 0, so XOR-ing the whole array cancels every pair and leaves xorAll = a ^ b, where a and b are the two single numbers. That alone does not separate them, but it tells us where they differ.
- XOR all numbers to get
xorAll. Sincea != b, it is not 0. - Take its lowest set bit:
lowestBit = xorAll & -xorAll.aandbdiffer in this bit, so exactly one of them has it. - XOR together only the numbers that have this bit set. Both copies of every pair fall in the same group and cancel, and exactly one of
a,bis in the group. The result is that number; call itfirst. - The other one is
xorAll ^ first.
For [1,2,1,3,2,5]: xorAll = 3 ^ 5 = 6 (binary 110), so lowestBit = 2. The numbers with bit 2 set are 2, 3, 2, whose XOR is 3; the other answer is 6 ^ 3 = 5.
In C++, -xorAll overflows a signed int when xorAll is INT_MIN, so the bit work is done on unsigned int there.
Complexity: O(n) time, where n is the length of nums, with two passes. O(1) extra space.
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
# Pairs cancel out, so xor_all = a ^ b for the two single numbers a and b.
xor_all = 0
for x in nums:
xor_all ^= x
# a != b, so xor_all has a set bit; take the lowest one. a and b differ in that bit.
lowest_bit = xor_all & -xor_all
# Split the numbers by that bit: a and b land in different groups, each pair in the same group.
first = 0
for x in nums:
if x & lowest_bit:
first ^= x
return [first, xor_all ^ first]
Now write it from memory
Close the write-up and solve it yourself against the tests.