Ticker

6/recent/ticker-posts

Leetcode-3158. 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.


The given task is to determine the bitwise XOR of all numbers that appear twice in the array `nums`. If no number appears twice, the function returns 0. The provided solution uses sorting and iteration to solve the problem.

The code begins by initializing a variable `sum` to 0, which will store the cumulative XOR of duplicate numbers. The array `nums` is then sorted in ascending order using `sort(nums.begin(), nums.end())`. Sorting helps in efficiently identifying consecutive duplicate numbers in a single pass through the array.

Next, the solution iterates over the sorted array using a `for` loop from index 0 to `n-2` (where `n` is the size of the array). During the iteration, if the current element (`nums[i]`) is equal to the next element (`nums[i+1]`), it is identified as a duplicate. The duplicate number is then XORed with `sum` using the operation `sum = nums[i] ^ sum`.

Finally, the function returns the value of `sum`. This represents the XOR of all duplicate numbers in the array. If no duplicates are found, `sum` remains 0, and the function returns 0 as required.

Example Explanation:

1. Input: `nums = [1, 2, 1, 3]`  

   Execution: After sorting, the array becomes `[1, 1, 2, 3]`. The loop identifies `1` as a duplicate and calculates `sum = 1 ^ 0 = 1`. No other duplicates exist, so the function returns `1`.  

2. Input: `nums = [1, 2, 3]`  

   Execution: After sorting, the array remains `[1, 2, 3]`. No duplicates are found, so the function returns `0`.

3. Input:`nums = [1, 2, 2, 1]`  

 Execution: After sorting, the array becomes `[1, 1, 2, 2]`. The loop identifies duplicates `1` and `2`. It calculates `sum = 1 ^ 0 = 1`, then `sum = 2 ^ 1 = 3`. The function returns `3`.


This solution is straightforward but requires  O(n log n) time due to sorting. It efficiently uses XOR to calculate the desired result while maintaining constant space apart from the input array.

CODE:

class Solution {
public:
    int duplicateNumbersXOR(vector<int>& nums) {
        int i;
        int n=nums.size();
        int sum=0; sort(nums.begin(),nums.end());
       for(i=0;i<n-1;i++){
       if(nums[i]==nums[i+1]){
           sum=nums[i]^sum;
           }
           }
        return sum;
               
    }
};


YOUTUBE:



Post a Comment

0 Comments