Find the XOR of Numbers Which Appear Twice
EasyUpdated: Aug 2, 2025
Practice on:
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.
Examples
Example 1
Input: nums = [1,2,1,3]
Output: 1
Explanation:
The only number that appears twice in `nums` is 1.
Example 2
Input: nums = [1,2,3]
Output: 0
Explanation:
No number appears twice in `nums`.
Example 3
Input: nums = [1,2,2,1]
Output: 3
Explanation:
Numbers 1 and 2 appeared twice. `1 XOR 2 == 3`.
Constraints
1 <= nums.length <= 501 <= nums[i] <= 50- Each number in
numsappears either once or twice.
Solution
Method 1 – Hash Map Counting and XOR
Intuition
We need to find all numbers that appear exactly twice in the array and return their XOR. We can use a hash map (or array) to count occurrences, then XOR all numbers with count 2.
Approach
- Use a hash map (or array) to count the occurrences of each number in nums.
- Initialize ans = 0.
- For each number with count 2, XOR it into ans.
- Return ans (if no number appears twice, ans will be 0).
Code
C++
class Solution {
public:
int duplicateNumbersXOR(vector<int>& nums) {
unordered_map<int, int> cnt;
for (int x : nums) cnt[x]++;
int ans = 0;
for (auto& [k, v] : cnt) if (v == 2) ans ^= k;
return ans;
}
};
Go
func duplicateNumbersXOR(nums []int) int {
cnt := map[int]int{}
for _, x := range nums { cnt[x]++ }
ans := 0
for k, v := range cnt {
if v == 2 { ans ^= k }
}
return ans
}
Java
class Solution {
public int duplicateNumbersXOR(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int ans = 0;
for (var e : cnt.entrySet()) if (e.getValue() == 2) ans ^= e.getKey();
return ans;
}
}
Kotlin
class Solution {
fun duplicateNumbersXOR(nums: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
for (x in nums) cnt[x] = cnt.getOrDefault(x, 0) + 1
var ans = 0
for ((k, v) in cnt) if (v == 2) ans = ans xor k
return ans
}
}
Python
class Solution:
def duplicateNumbersXOR(self, nums: list[int]) -> int:
from collections import Counter
cnt = Counter(nums)
ans = 0
for k, v in cnt.items():
if v == 2:
ans ^= k
return ans
Rust
impl Solution {
pub fn duplicate_numbers_xor(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
let mut cnt = HashMap::new();
for &x in &nums { *cnt.entry(x).or_insert(0) += 1; }
let mut ans = 0;
for (&k, &v) in &cnt {
if v == 2 { ans ^= k; }
}
ans
}
}
TypeScript
class Solution {
duplicateNumbersXOR(nums: number[]): number {
const cnt: Record<number, number> = {};
for (const x of nums) cnt[x] = (cnt[x] || 0) + 1;
let ans = 0;
for (const k in cnt) if (cnt[k] === 2) ans ^= +k;
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n)— One pass to count, one pass to XOR. - 🧺 Space complexity:
O(n)— For the count map.