PIXELBANKv8.2.1
Menu

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=result2result = result \oplus 2, result=result2result = result \oplus 2, result=result1result = result \oplus 1.
  • Since aa=0a \oplus a = 0 and a0=aa \oplus 0 = a, the XOR operation cancels out the duplicate elements, leaving only the single element: 0221=001=10 \oplus 2 \oplus 2 \oplus 1 = 0 \oplus 0 \oplus 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

Test Results

0/0
Run code to see test results.