Set Mismatch (LeetCode 645): Solution and Explanation
An array should hold each number from 1 to n once, but one number was replaced by a copy of another. Return the duplicated number and the missing number as [duplicate, missing].
Intuition
A hash set solves this directly: the first value you try to add twice is the duplicate, and the one number from 1 to n that never got added is missing. That costs O(n) extra space.
The values themselves are in the range 1..n, which matches the indices 0..n-1. So the array can double as its own set: value v owns slot v - 1.
To mark v as seen without losing the number stored in slot v - 1, flip that slot's sign. The magnitude stays readable through abs(), and the sign becomes a one-bit flag.
If a slot is already negative when you arrive, its owner has been seen before, so that is the duplicate. After one pass, exactly one slot is still positive, and its owner is the missing number.
Approach: Sign marking in place
- Set
dup = -1andmissing = -1. - For each
num, computeidx = abs(num) - 1. - If
nums[idx] < 0, recorddup = abs(num). Otherwise negatenums[idx]. - Scan indices again; the index
iwhose value is still positive givesmissing = i + 1. - Return
[dup, missing].
Step-by-step example
nums = [1,2,2,4]
- Read 1: flip slot 0. The array becomes [-1,2,2,4].
- Read 2: flip slot 1. The array becomes [-1,-2,2,4].
- Read 2 again: slot 1 is already negative, so dup = 2.
- Read 4: flip slot 3. The array becomes [-1,-2,2,-4].
- Scan: slot 2 is the only positive one, so missing = 3. Return [2,3].
Code: Python, Java, C++
1class Solution:
2 def findErrorNums(self, nums: List[int]) -> List[int]:
3 dup, missing = -1, -1
4 for num in nums:
5 idx = abs(num) - 1
6 if nums[idx] < 0:
7 dup = abs(num)
8 else:
9 nums[idx] = -nums[idx]
10 for i in range(len(nums)):
11 if nums[i] > 0:
12 missing = i + 1
13 return [dup, missing]1class Solution {
2 public int[] findErrorNums(int[] nums) {
3 int dup = -1, missing = -1;
4 for (int num : nums) {
5 int idx = Math.abs(num) - 1;
6 if (nums[idx] < 0) {
7 dup = Math.abs(num);
8 } else {
9 nums[idx] = -nums[idx];
10 }
11 }
12 for (int i = 0; i < nums.length; i++) {
13 if (nums[i] > 0) {
14 missing = i + 1;
15 }
16 }
17 return new int[]{dup, missing};
18 }
19}1class Solution {
2public:
3 vector<int> findErrorNums(vector<int>& nums) {
4 int dup = -1, missing = -1;
5 for (int num : nums) {
6 int idx = abs(num) - 1;
7 if (nums[idx] < 0) {
8 dup = abs(num);
9 } else {
10 nums[idx] = -nums[idx];
11 }
12 }
13 for (int i = 0; i < (int)nums.size(); i++) {
14 if (nums[i] > 0) {
15 missing = i + 1;
16 }
17 }
18 return {dup, missing};
19 }
20};Time and space complexity
O(n)
Two linear passes over the array.
O(1)
Only two integers beyond the input. The input array is modified in place, which LeetCode allows here; restore signs afterwards if the caller needs it intact.
Other approaches
Hash set or count array (time O(n), space O(n))
Count how many times each value appears. The value with count 2 is the duplicate, the value with count 0 is missing. Simple and does not modify the input.
Math with sums (time O(n), space O(1))
Let d be the duplicate and m the missing number. The sum of nums minus n(n+1)/2 equals d - m, and the sum of squares difference equals d^2 - m^2. Dividing gives d + m, then solve the pair.
XOR partitioning (time O(n), space O(1))
XOR all values with 1..n to get d XOR m, split numbers by one set bit, and XOR each group to isolate d and m. A final pass tells which one is the duplicate.
Common mistakes
- Using
nums[num - 1]withoutabs(). Earlier flips can make num negative, which produces an invalid index. - Negating a slot twice. If you flip unconditionally, the duplicate's slot turns positive again and looks like the missing number.
- Returning the answer in the wrong order. The expected format is [duplicate, missing].
- Assuming the input is sorted. The duplicate and the missing number can be anywhere, so a neighbor comparison is not enough.
Frequently asked questions
Why can a slot hold a flag and a value at once?
All values are positive, so the sign carries no information originally. Flipping it stores one extra bit, while abs() still recovers the original value for when that slot is read later.
Can the missing number be n?
Yes. Then slot n - 1 is never flipped and stays positive, so the scan reports n. The same holds for 1 and every value in between.
Is modifying the input acceptable in an interview?
Usually yes if you say so. If not, use a count array, or restore the array by taking abs() of every element at the end.