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.

The returned array should contain [duplicate, missing] where duplicate is the number that appears twice and missing is the number that should be present but isn't.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,2,4]
Output: [2,3]
💡 Note: Number 2 appears twice (duplicate), number 3 is missing from the sequence 1,2,3,4
Example 2 — Different Position
$ Input: nums = [1,1]
Output: [1,2]
💡 Note: Number 1 appears twice (duplicate), number 2 is missing from the sequence 1,2
Example 3 — Larger Array
$ Input: nums = [3,2,3,4,6,5]
Output: [3,1]
💡 Note: Number 3 appears twice (duplicate), number 1 is missing from the sequence 1,2,3,4,5,6

Constraints

  • 2 ≤ nums.length ≤ 104
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Set Mismatch - Hash Approach INPUT Original Set: {1, 2, 3, 4} nums array (with error): 1 [0] 2 [1] 2 [2] 4 [3] Duplicate: 2 appears twice Missing: 3 is absent Input: nums = [1, 2, 2, 4] Find duplicate and missing numbers in the array n = 4 (array length) ALGORITHM STEPS 1 Create Hash Map Count frequency of each num map = {1:1, 2:2, 4:1} Key: number, Value: count 2 has count 2 (duplicate!) 2 Find Duplicate Number with count = 2 3 Find Missing Check 1 to n, find count = 0 Check 1: count=1 OK Check 2: count=2 DUP Check 3: count=0 MISSING Check 4: count=1 OK 4 Return Result Return [duplicate, missing] Time: O(n) | Space: O(n) FINAL RESULT Found Values: DUPLICATE 2 MISSING 3 Output Array: 2 3 [2, 3] OK - Solution Found! Key Insight: Using a hash map to count frequencies allows O(1) lookup for each number. The duplicate has count 2, while the missing number (in range 1 to n) has count 0. This approach trades O(n) space for O(n) time, making it efficient for large arrays compared to O(n^2) brute force approaches. TutorialsPoint - Set Mismatch | Hash Approach
Asked in
Amazon 35 Google 28 Microsoft 22 Apple 18
185.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen