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.
- Initialize a variable
resultto 0. - Iterate through every number in the array.
- Use the XOR operator (
^) to combine the current number with theresult. - Because $A oplus A = 0$ and $A oplus 0 = A$, all pairs will cancel each other out, leaving only the "Lone Survivor."
- Print the final
result.
01EXAMPLE 1
Input
[2, 2, 1]Output
1Explanation: 2 paired off, 1 is single.
Constraints
- Solve in O(n) time.
- Solve in O(1) extra space (no Map/Object).
ArraysBitwiseAlgorithms
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[2,2,1]
Expected Output
1
Click RUN to test your solution