Tuesday, March 2, 2021

[LeetCode] Set Mismatch

Problem: You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

Example:

Input: nums = [1,2,2,4]
Output: [2,3]
Input: nums = [1,1]
Output: [1,2]


Approach: This problem is similar to Finding two elements that appears only once. We can use XOR to find these numbers. We just need to take care of the order in which we want to return these numbers as first number must be the repeated one and second is the missing one.

That's all!


Implementation in C#:

    public int[] FindErrorNums(int[] nums) 

    {

        int xor = 0;

        for (int i = 0; i < nums.Length; ++i)

        {

            xor ^= ((i + 1) ^ nums[i]);

        }

        int setBit = xor & ~(xor - 1);

        int[] result = new int[2];

        for (int i = 0; i < nums.Length; ++i)

        {

            if ((nums[i] & setBit) != 0)

            {

                result[0] ^= nums[i];

            }

            else

            {

                result[1] ^= nums[i];

            }

            if (((i + 1) & setBit) != 0)

            {

                result[0] ^= (i + 1);

            }

            else

            {

                result[1] ^= (i + 1);

            }

        }

        for (int i = 0; i < nums.Length; ++i)

        {

            if (result[1] == nums[i])

            {

                int temp = result[1];

                result[1] = result[0];

                result[0] = temp;

                

                return result;

            }

        }

        return result;

    }


Complexity: O(n)


No comments:

Post a Comment