Set Mismatch

Set Mismatch

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.

LeetCode Problem - 645: Link | Click Here

class Solution {
    public int[] findErrorNums(int[] nums) {
        // Get the length of the input array
        int len = nums.length;

        // Create an array to store the result, containing the repeated number and the missing number
        int[] resultArray = new int[2];

        // Create an array to keep track of occurrences of each number from 1 to len
        int[] occurrences = new int[len + 1];

        // Iterate through the input array to find the repeated number
        for (int i = 0; i < len; i++) {
            // If the current number has not occurred yet, mark its occurrence
            if (occurrences[nums[i]] == 0) {
                occurrences[nums[i]] = 1;
            } else {
                // If the current number has occurred before, it is the repeated number
                resultArray[0] = nums[i];
            }
        }

        // Iterate through the occurrences array to find the missing number
        for (int i = 1; i <= len; i++) {
            // If the occurrence is 0, then i is the missing number
            if (occurrences[i] == 0) {
                resultArray[1] = i;
                break;
            }
        }

        // Return the array containing the repeated and missing numbers
        return resultArray;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!