645. Set Mismatch LeetCode Solution

In this guide, you will get 645. Set Mismatch LeetCode Solution with the best time and space complexity. The solution to Set Mismatch problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Set Mismatch solution in C++
  4. Set Mismatch solution in Java
  5. Set Mismatch solution in Python
  6. Additional Resources
645. Set Mismatch LeetCode Solution image

Problem Statement of 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.

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

Constraints:

2 <= nums.length <= 104
1 <= nums[i] <= 104

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

645. Set Mismatch LeetCode Solution in C++

class Solution {
 public:
  vector<int> findErrorNums(vector<int>& nums) {
    int duplicate;

    for (const int num : nums)
      if (nums[abs(num) - 1] < 0)
        duplicate = abs(num);
      else
        nums[abs(num) - 1] *= -1;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] > 0)
        return {duplicate, i + 1};

    throw;
  }
};
/* code provided by PROGIEZ */

645. Set Mismatch LeetCode Solution in Java

class Solution {
  public int[] findErrorNums(int[] nums) {
    int duplicate = 0;

    for (final int num : nums) {
      if (nums[Math.abs(num) - 1] < 0)
        duplicate = Math.abs(num);
      else
        nums[Math.abs(num) - 1] *= -1;
    }

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] > 0)
        return new int[] {duplicate, i + 1};

    throw new IllegalArgumentException();
  }
}
// code provided by PROGIEZ

645. Set Mismatch LeetCode Solution in Python

class Solution:
  def findErrorNums(self, nums: list[int]) -> list[int]:
    for num in nums:
      if nums[abs(num) - 1] < 0:
        duplicate = abs(num)
      else:
        nums[abs(num) - 1] *= -1

    for i, num in enumerate(nums):
      if num > 0:
        return [duplicate, i + 1]
# code by PROGIEZ

Additional Resources

See also  335. Self Crossing LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.