💡 Suggested Approach & Sample Answer
Optimal Bit Manipulation Approach (XOR):
- Leverage the mathematical properties of the bitwise XOR (^) operator: x ^ x = 0 and x ^ 0 = x.
def single_number(nums: list[int]) -> int:
result = 0
for num in nums:
result ^= num
return result
Complexity & Key Logic:
- Time Complexity: O(N) single linear scan over the array.
- Space Complexity: O(1) constant auxiliary space.
- Algorithm Details:
- XOR is commutative and associative: the order of operations does not matter (a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b).
- Every number that appears twice cancels itself out to 0.
- The single unique element remains as the final value in result.