Set Mismatch (LeetCode 645): Solution and Explanation

Easy
Array
Hash Table
Bit Manipulation
Sorting

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

  1. Set dup = -1 and missing = -1.
  2. For each num, compute idx = abs(num) - 1.
  3. If nums[idx] < 0, record dup = abs(num). Otherwise negate nums[idx].
  4. Scan indices again; the index i whose value is still positive gives missing = i + 1.
  5. Return [dup, missing].

Step-by-step example

nums = [1,2,2,4]
  1. Read 1: flip slot 0. The array becomes [-1,2,2,4].
  2. Read 2: flip slot 1. The array becomes [-1,-2,2,4].
  3. Read 2 again: slot 1 is already negative, so dup = 2.
  4. Read 4: flip slot 3. The array becomes [-1,-2,2,-4].
  5. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Two linear passes over the array.

Space

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] without abs(). 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.