Set Mismatch - Hash Table - Easy - LeetCode
💻 coding

Set Mismatch - Hash Table - Easy - LeetCode

1 min read 171 words
1 min read
ShareWhatsAppPost on X
  • 1The set S contains numbers from 1 to n, but one number is duplicated and another is missing due to a data error.
  • 2The task is to identify the duplicated number and the missing number from the given array nums.
  • 3The solution uses a HashSet for tracking numbers, achieving O(n) time complexity and O(n) space complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The set S contains numbers from 1 to n, but one number is duplicated and another is missing due to a data error."

Set Mismatch - Hash Table - Easy - LeetCode

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in the repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1: Input: nums = [1,2,2,4] Output: [2,3] Note: The given array size will in the range [2, 10000]. The given array's numbers won't have any order.

public class Solution {
 public int[] FindErrorNums(int[] nums) {
 var set = new HashSet<int>();
 int duplicate = 0;
 long sum = 0;
 for(int i=0;i<nums.Length;i++){
 if(set.Contains(nums[i])){
 duplicate = nums[i];
 }
 else{
 set.Add(nums[i]);
 }
 sum+=nums[i];
 }
 
 long expectedSum = (nums.Length * (nums.Length+1))/2;
 var ans = new int[2];
 ans[0]=duplicate;
 ans[1]=duplicate + (int)(expectedSum-sum);
 
 return ans;
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 29 September 2020 · 1 min read · 171 words

Part of AskGif Blog · coding

You might also like