Set Mismatch - Problem
You're given an array nums that was supposed to contain all integers from 1 to n exactly once, but something went wrong! One number got duplicated, which means another number went missing.
Your mission: Find both the duplicate number (appears twice) and the missing number (doesn't appear at all).
Example: If nums = [1,2,2,4], then:
- The duplicate is
2(appears twice) - The missing number is
3(should be there but isn't) - Return
[2,3]
Goal: Return an array [duplicate, missing] where the first element is the number that appears twice, and the second is the number that's missing.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,2,2,4]
โบ
Output:
[2,3]
๐ก Note:
The number 2 appears twice (duplicate) and the number 3 is missing from the sequence 1,2,3,4.
example_2.py โ Different Duplicate
$
Input:
nums = [1,1]
โบ
Output:
[1,2]
๐ก Note:
For array of length 2, we should have [1,2]. The number 1 is duplicated and 2 is missing.
example_3.py โ Larger Array
$
Input:
nums = [3,2,3,4,6,5]
โบ
Output:
[3,1]
๐ก Note:
Array should be [1,2,3,4,5,6]. The number 3 appears twice and 1 is missing.
Constraints
- 2 โค nums.length โค 104
- 1 โค nums[i] โค 104
- nums contains n distinct numbers plus one duplicate
- The array represents numbers from 1 to n with exactly one duplicate and one missing
Visualization
Tap to expand
Understanding the Visualization
1
Take Attendance
Call out each student number and mark who responds
2
Notice Duplicate
Student #2 responds twice - suspicious!
3
Find Missing
Use math: expected total responses minus actual responses plus duplicate
4
Solve Mystery
Student #2 answered twice, Student #3 is absent
Key Takeaway
๐ฏ Key Insight: Combine hash table duplicate detection with mathematical sum relationships to solve both parts of the problem efficiently in one pass!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code