Single Number Ii
To solve this coding challenge, we need to find an element in the given integer array
that appears exactly once, while every other element appears three times. We need an approach that operates with linear runtime complexity (O(n)) and uses only constant extra space (O(1)).
nums
# Explanation
The problem asks for a solution that works efficiently and using constant space. A very effective way to approach problems where elements repeat a specific number of times is using bitwise operations. Bitwise operations allow us to manipulate individual bits of numbers directly and are typically very fast. The core idea behind the solution is using two variables to track the count bits for the numbers seen so far. Here's how it works step-by-step:-
Initialization
: We start by initializing two variables,
ones
twos
-
Iterating Through the Array
: We iterate through each number in the array and update the
ones
twos
- Bitwise Operations :
-
ones
-
twos
-
Clearing the Bits
: After updating
ones
twos
ones
twos
-
Returning the Result
: By the end of the iteration,
ones
-
Initialize
ones
twos
- Iterate through each number in the array.
-
Compute
new_ones
-
Compute
new_twos
-
Update
ones
new_ones
-
Update
twos
new_twos
-
Clear bits from
ones
twos
-
Return
ones
Here’s the complete pseudocode for the solution with comments:
- Initialization :
-
ones = 0
-
twos = 0
- Loop through each number :
-
For each number, update
new_ones
-
(ones ^ num)
ones
num
num
-
~twos
twos
twos
-
The result is the new candidate for the bits in
ones
-
Update
new_twos
-
(twos ^ num)
twos
num
num
-
~new_ones
ones
-
Assign
new_ones
ones
new_twos
twos
- Result after loop :
-
After all iterations,
ones
# Detailed Steps in Pseudocode
# Pseudocode for finding the single number that appears exactly once
# Initialize two variables to store counts of bits appearing once and twice
ones = 0
twos = 0
# Iterate through each number in the input array nums
for num in nums:
# Update ones to include the current num only if it has not been included twice
new_ones = (ones ^ num) & ~twos
# Update twos to include the current num only if it has not been included once
new_twos = (twos ^ num) & ~new_ones
# Assign the new values to ones and twos for the next iteration
ones = new_ones
twos = new_twos
# The number that appears exactly once will be in ones
return ones