#137

Single Number II

Medium
ArrayBit ManipulationBit ManipulationArray
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)

The optimal solution uses bit manipulation to find the unique number. By leveraging the properties of binary representation, we can efficiently count bits and determine the unique number without extra space.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two variables, ones and twos, to track the bits seen once and twice.
  2. 2Step 2: Iterate through each number in the array, updating ones and twos based on the current number's bits.
  3. 3Step 3: Use bitwise operations to ensure that bits that appear three times are cleared from ones and twos.
  4. 4Step 4: After processing all numbers, ones will contain the unique number.
solution.py8 lines
1# Full working Python code
2
3def singleNumber(nums):
4    ones, twos = 0, 0
5    for num in nums:
6        ones = (ones ^ num) & ~twos
7        twos = (twos ^ num) & ~ones
8    return ones

Complexity note: This complexity is linear because we only pass through the array once, and we use constant space for the variables.

  • 1Using bit manipulation can significantly reduce time complexity.
  • 2Tracking occurrences using bitwise operations is efficient.

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