Find the XOR of Numbers Which Appear Twice - Problem
You're given an array nums where each number appears either once or twice. Your task is to find all numbers that appear exactly twice and return their bitwise XOR.
If no number appears twice, return 0.
Key Points:
- Numbers can appear 1 or 2 times only
- XOR all the duplicates together
- XOR has useful properties:
a โ a = 0anda โ 0 = a
Example: For array [1, 2, 1, 3], only 1 appears twice, so return 1.
Input & Output
example_1.py โ Basic case with one duplicate
$
Input:
nums = [1, 2, 1, 3]
โบ
Output:
1
๐ก Note:
Only the number 1 appears twice in the array. So we return 1 โ 0 = 1.
example_2.py โ Multiple duplicates
$
Input:
nums = [1, 2, 3, 1, 2, 3]
โบ
Output:
0
๐ก Note:
Numbers 1, 2, and 3 all appear twice. The XOR is 1 โ 2 โ 3 = 0.
example_3.py โ No duplicates
$
Input:
nums = [1, 2, 3, 4]
โบ
Output:
0
๐ก Note:
No number appears twice, so we return 0 by default.
Constraints
- 1 โค nums.length โค 50
- 1 โค nums[i] โค 50
- Each number appears either once or twice
Visualization
Tap to expand
Understanding the Visualization
1
Guest Arrives
First time seeing a number - add to set
2
Guest Returns
Second time seeing a number - XOR with result
3
Guest Leaves
Remove from set since we've processed the duplicate
Key Takeaway
๐ฏ Key Insight: Use XOR's self-canceling property (a โ a = 0) combined with hash set for O(n) duplicate detection.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code