#260

Single Number III

Medium
ArrayBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using bit manipulation, we can efficiently find the two unique numbers in linear time and constant space. The key is to leverage the properties of XOR to separate the two unique numbers.

⚙️

Algorithm

3 steps
  1. 1Step 1: XOR all numbers to get a combined result of the two unique numbers (let's call it xorResult).
  2. 2Step 2: Find a bit that is set (1) in xorResult. This bit will help us differentiate the two unique numbers.
  3. 3Step 3: Partition the original numbers into two groups based on the set bit and XOR each group to find the two unique numbers.
solution.py15 lines
1# Full working Python code
2
3def singleNumber(nums):
4    xorResult = 0
5    for num in nums:
6        xorResult ^= num
7    # Get the rightmost set bit
8    diff = xorResult & -xorResult
9    num1, num2 = 0, 0
10    for num in nums:
11        if num & diff:
12            num1 ^= num
13        else:
14            num2 ^= num
15    return [num1, num2]

Complexity note: This complexity is linear because we only pass through the list a constant number of times, and we use a fixed amount of extra space.

  • 1XOR is a powerful tool for problems involving pairs or unique elements.
  • 2Identifying a distinguishing bit helps in segregating elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.