Skip to content

3158. Find the XOR of Numbers Which Appear Twice 👍

  • Time: $O(n)$
  • Space: $O(50) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int duplicateNumbersXOR(vector<int>& nums) {
    constexpr int kMax = 50;
    int ans = 0;
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    for (int num = 1; num <= kMax; ++num)
      if (count[num] == 2)
        ans ^= num;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int duplicateNumbersXOR(int[] nums) {
    final int kMax = 50;
    int ans = 0;
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    for (int num = 1; num <= kMax; ++num)
      if (count[num] == 2)
        ans ^= num;

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def duplicateNumbersXOR(self, nums):
    count = collections.Counter(nums)
    return functools.reduce(
        operator.xor, [num for num, freq in count.items() if freq == 2],
        0)