3158. Find the XOR of Numbers Which Appear Twice LeetCode Solution

In this guide, you will get 3158. Find the XOR of Numbers Which Appear Twice LeetCode Solution with the best time and space complexity. The solution to Find the XOR of Numbers Which Appear Twice problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find the XOR of Numbers Which Appear Twice solution in C++
  4. Find the XOR of Numbers Which Appear Twice solution in Java
  5. Find the XOR of Numbers Which Appear Twice solution in Python
  6. Additional Resources
3158. Find the XOR of Numbers Which Appear Twice LeetCode Solution image

Problem Statement of Find the XOR of Numbers Which Appear Twice

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 <= 50
1 <= nums[i] <= 50
Each number in nums appears either once or twice.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(50) = O(1)

3158. Find the XOR of Numbers Which Appear Twice LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

3158. Find the XOR of Numbers Which Appear Twice LeetCode Solution in Java

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;
  }
}
// code provided by PROGIEZ

3158. Find the XOR of Numbers Which Appear Twice LeetCode Solution in Python

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],
)
# code by PROGIEZ

Additional Resources

See also  3159. Find Occurrences of an Element in an Array LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.