Find the XOR of Numbers Which Appear Twice - Problem

You are given an array nums, where each number in the array appears either once or twice.

Return the bitwise XOR of all the numbers that appear twice in the array, or 0 if no number appears twice.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,2]
Output: 2
💡 Note: Only the number 2 appears twice in the array, so we return 2
Example 2 — Multiple Duplicates
$ Input: nums = [1,2,1,3]
Output: 1
💡 Note: Only the number 1 appears twice, so we return 1
Example 3 — No Duplicates
$ Input: nums = [1,2,3]
Output: 0
💡 Note: No number appears twice, so we return 0

Constraints

  • 1 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 50

Visualization

Tap to expand
XOR of Numbers Appearing Twice INPUT nums = [1, 2, 3, 2] 1 idx 0 2 idx 1 3 idx 2 2 idx 3 = Duplicate Number Counts: 1 appears: 1 time 2 appears: 2 times 3 appears: 1 time Only 2 appears twice! ALGORITHM STEPS 1 Create Hash Map Track count of each num 2 Iterate Array Increment count for each 3 Find Duplicates Check count == 2 4 XOR Duplicates result ^= duplicate_num Hash Map State: Key | Count 1 | 1 2 | 2 [OK] 3 | 1 FINAL RESULT XOR Calculation: Duplicates found: [2] result = 0 XOR 2 result = 2 Binary View: 0 = 0000 2 = 0010 XOR = 0010 = 2 Output: 2 Key Insight: Use a hash map to count occurrences. Numbers appearing twice are XORed together. If multiple duplicates exist (e.g., [1,1,2,2]), result = 1 XOR 2 = 3. XOR is associative! Time: O(n) | Space: O(n) for hash map storage TutorialsPoint - Find the XOR of Numbers Which Appear Twice | Hash Map Approach
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~10 min Avg. Time
450 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