439. Set Mismatch
An array nums of length n was meant to contain every integer from 1 to n exactly once. During a faulty copy, one entry got overwritten: some value now appears twice, and because of that another value from the range never appears at all.
Your function receives nums and returns the pair [duplicate, missing] — first the value that occurs twice, then the value that is absent.
Example 1:
Input: nums = [1, 2, 2, 4]
Output: [2, 3]
Explanation: 2 shows up twice and 3 never shows up, so the answer is [2, 3].
Example 2:
Input: nums = [1, 1]
Output: [1, 2]
Explanation: For n = 2 the array should hold 1 and 2; instead 1 is doubled and 2 is missing.
Constraints:
- 2 ≤ nums.length ≤ 10⁴
- 1 ≤ nums[i] ≤ nums.length
- Exactly one value appears twice and exactly one value from 1..n is missing.
Hints:
Every value lives in the small range 1..n, so an occurrence count per value can only be 0, 1, or 2. A counting array of size n finds both answers in one extra pass.
Want O(1) extra space? Each value x is also a valid position x − 1. Visit each value and flip the sign at its position: seeing an already-negative cell means x is the duplicate, and the position that stays positive marks the missing value.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [1, 2, 2, 4]
Expected output: [2, 3]