The Lone Survivor

HardAcc. 68.9%
+50 XP 30

The Lone Survivor (XOR Paradox)

In a crowded field of pairs, one element stands alone. Every number in your list appears exactly twice, except for one solitary value. While you could use a Map to count them, there is a brilliant bitwise trick using the XOR ($oplus$) operator that can find the survivor instantly without any extra memory!

The Assignment

Your mission is to find the single element. Your function receives an array nums.

  1. Initialize a variable result to 0.
  2. Iterate through every number in the array.
  3. Use the XOR operator (^) to combine the current number with the result.
  4. Because $A oplus A = 0$ and $A oplus 0 = A$, all pairs will cancel each other out, leaving only the "Lone Survivor."
  5. Print the final result.

01EXAMPLE 1

Input[2, 2, 1]
Output1

Explanation: 2 paired off, 1 is single.

Constraints

  • Solve in O(n) time.
  • Solve in O(1) extra space (no Map/Object).
ArraysBitwiseAlgorithms
JavaScript
Loading...
1 Hidden

Input Arguments

nums[2,2,1]

Expected Output

1

Click RUN to test your solution