Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Use Bit manipulation.
Learned from: https://velog.io/@hojin11choi/TIL-Python-Bit-manipulation

class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for num in nums:
ans ^= num
return ans
61/61 cases passed (107 ms)
Your runtime beats 92.88 % of python3 submissions
Your memory usage beats 20.35 % of python3 submissions (19.9 MB)
Your solution for finding the single number in an array where every other element appears twice is both correct and efficient. You've used the bitwise XOR (^) operation, which is a clever and optimal way to solve this problem with a linear runtime complexity (O(n)) and constant extra space (O(1)).
Let's explain how your solution works:
Bitwise XOR Operation (^):
x, x ^ x = 0, and x ^ 0 = x.Using XOR to Find the Single Number:
ans ^= num), every number that appears twice will effectively cancel itself out (because x ^ x = 0).[4,1,2,1,2], the operations are essentially (4^1^2^1^2). Both 1's and 2's cancel themselves out, leaving 4 as the result.Your Implementation:
ans to 0. This is important because XOR-ing any number with 0 gives the number itself.ans.ans contains the single number that does not have a duplicate in the array.In conclusion, your approach efficiently solves the problem in the required constraints of linear time complexity and constant space complexity. It's an excellent example of the power of bitwise operations in certain algorithmic problems.