📘
Single Number
Given an array where every element appears twice except one, find the single element. Must run in O(n) time and O(1) space.
Example:
Input:
2,2,1
Output:
1
Reasoning:
- We initialize a variable to 0, which will hold the result of the bitwise XOR operation.
- We iterate over the input array, applying the XOR operation to each element: result=result⊕2, result=result⊕2, result=result⊕1.
- Since a⊕a=0 and a⊕0=a, the XOR operation cancels out the duplicate elements, leaving only the single element: 0⊕2⊕2⊕1=0⊕0⊕1=1.
- The final output is the result of the XOR operation, which is the single element in the array.
Constraints:
- 1 <= len(nums) <= 3 * 10^4
- -3 * 10^4 <= nums[i] <= 3 * 10^4
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.