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 = 0 and a โŠ• 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
Hash Set Solution OverviewProcess: [1, 2, 1, 3]1Add to set2Add to set1XOR & remove3Add to setSet Evolution: {} โ†’ {1} โ†’ {1,2} โ†’ {2} โ†’ {2,3}Final Result10 โŠ• 1 = 1Key Properties:โœ… O(n) time - single passโœ… O(n) space - hash setโœ… XOR properties: a โŠ• a = 0โœ… Elegant duplicate handling
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
24.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen