Set Mismatch

Gulshan KumarGulshan Kumar
2 min read

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;
    }
}
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.