LeetCode 137 - Single Number II:
Given an integer array nums
where every element appears three times except for one, which appears exactly once. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space.
To solve this problem, we need to use bit manipulation to ensure both linear runtime and constant space complexity. Here’s the thought process:
ones
and twos
.ones
will store the bits which have appeared exactly once.twos
will store the bits which have appeared exactly twice.ones
and twos
.By the end of the traversal, ones
will contain the bits of the number that appears exactly once.
def singleNumber(nums):
# Initialize two variables to store the bits
ones, twos = 0, 0
for num in nums:
# First appearance:
# Add num to 'ones' if it is not there in 'twos'
ones = (ones ^ num) & ~twos
# Second appearance:
# Add num to 'twos' if it is not there in 'ones'
twos = (twos ^ num) & ~ones
return ones
# Example usage
nums = [2, 2, 3, 2]
print(singleNumber(nums)) # Output: 3
ones
, twos
are initialized to 0
.num
):
ones
only if the current number is not already in twos
. This ensures that ones
holds bits for numbers appearing the first time.twos
only if the current number is not already in ones
. This ensures that twos
holds bits for numbers appearing the second time.ones
:
ones
will hold the bits of the number that appears exactly once in the array.n
is the number of elements in the input array nums
. We only pass through the array once.This solution ensures both the required linear runtime and constant extra space usage.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?