136. Single Number
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
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
Constraints:
1 <= nums.length <= 3 * 10^4
-3 * 10^4 <= nums[i] <= 3 * 10^4
To solve this problem efficiently, we can leverage the properties of the XOR bitwise operation:
a ^ a = 0
(XOR of a number with itself is 0)a ^ 0 = a
(XOR of a number with 0 is the number itself)def singleNumber(nums):
result = 0
for num in nums:
result ^= num
return result
result
to 0.nums
array.result
(i.e., result ^= num
).result
will contain the single number that appears only once.n
is the number of elements in the nums
array. We are iterating through each element exactly once.result
) regardless of the input size.This approach ensures both optimal time and space performance.
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?