Find the XOR of Numbers Which Appear Twice

Gulshan KumarGulshan Kumar
1 min read

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.

LeetCode Problem - 3158

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int duplicateNumbersXOR(int[] nums) {
        // Create a HashMap to store the frequency of each number in the array
        Map<Integer, Integer> map = new HashMap<>();

        // Iterate over each number in the array
        for (int num : nums) {
            // Increment the count of the number in the map
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        // Initialize a variable to hold the XOR of duplicate numbers
        int xor = 0;

        // Iterate over the keys in the map (unique numbers in the array)
        for (int num : map.keySet()) {
            // Get the frequency of the current number
            int value = map.get(num);

            // If the number appears exactly twice, XOR it with the current xor value
            if (value == 2) xor ^= num;
        }

        // Return the final XOR result
        return xor;
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.