Find the XOR of Numbers Which Appear Twice Problem
#3158
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3158.
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.
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
Approach: Counting
Keep a count for each value. The moment a value's count reaches 2, XOR it into the answer. Values that appear once are never XORed, and the answer is 0 if nothing repeats.
Complexity: O(n) time and O(M) extra space, where M is the largest value.
from collections import Counter
from functools import reduce
from operator import xor
class Solution:
def duplicateNumbersXOR(self, nums: List[int]) -> int:
cnt = Counter(nums)
return reduce(xor, [x for x, v in cnt.items() if v == 2], 0)