An array nums of length n was meant to hold every number from 1 to n exactly once, in some order. One mistake crept in: one of the numbers was overwritten with a copy of another. Now one value shows up twice and one value from 1 to n is gone.
Return a pair [dup, missing]: the value that appears twice, followed by the value that no longer appears.
Example 1
Input: nums = [4, 3, 3, 1] Output: [3, 2] Why: 3 is written twice and 2 never appears
2 more examples and the constraints
Example 2
Input: nums = [2, 2] Output: [2, 1] Why: the 1 was replaced by a second 2
Example 3
Input: nums = [1, 3, 4, 5, 5] Output: [5, 2] Why: 5 shows up twice; 2 is the gap
Constraints
- 2 ≤ nums.length ≤ 10,000
- 1 ≤ nums[i] ≤ nums.length
- Exactly one value appears twice and exactly one value from 1 to n is absent
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count every numberO(n)
- Mark slots with signsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Count every number | O(n) | Simple; costs an extra array | |
| Mark slots with signs | O(n) | Best; no extra memory |
n = length of nums. Both are linear; the difference is the O(n) count array.
Edge cases to test
- Only two numbers.
[2, 2]gives[2, 1]: the missing number can be 1. - Missing number is n.
[1, 2, 2]gives[2, 3]: the last slot is the one left positive. - Duplicate next to the gap.
[1, 1]gives[1, 2]; the order of the answer is always duplicate first. - Unsorted input. Neither approach sorts, so the order of nums does not matter.
Common mistakes
- Reading
nums[i]withoutabs, so a value that was already flipped gives a negative index. - Returning
[missing, dup]: the duplicate comes first. - Using a sum formula alone: the sum only gives dup − missing, not each value separately.
How to talk through it
- 1Clarify. Values are exactly 1 to n with one replaced? Duplicate first in the answer? May I modify nums?
- 2Give the simple answer. Count each number in an array of size n + 1, then look for counts 2 and 0.
- 3Point out the range. Since values are 1 to n, each value can mark its own slot in nums.
- 4Code the sign marking. Flip the slot of each value; an already negative slot is the duplicate; a positive slot at the end is the missing one.
- 5Test out loud. Run
[2, 2],[1, 2, 2]and Example 1 step by step.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?