You get an array nums of length n. Every number in it is between 1 and n, but some numbers may appear more than once, which means others never appear at all.
Return every number from 1 to n that is not in nums, from smallest to largest. If nothing is missing, return an empty list.
Example 1
Input: nums = [2, 5, 2, 1, 5] Output: [3, 4] Why: 1, 2 and 5 show up; 3 and 4 never do
2 more examples and the constraints
Example 2
Input: nums = [3, 3, 3] Output: [1, 2] Why: only 3 appears, three times
Example 3
Input: nums = [1] Output: [] Why: n = 1 and 1 is there, so nothing is missing
Constraints
- n is the length of nums, and 1 ≤ n ≤ 100,000
- 1 ≤ each nums[i] ≤ n
- Follow-up: O(n) time with no extra memory besides the answer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Set of seen valuesO(n)
- Mark slots with a minus signO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 100,000 numbers | Verdict |
|---|---|---|---|
| Set of seen values | O(n) | Clear; up to n extra entries | |
| Mark slots with a minus sign | O(n) | Best; no extra memory |
n = length of nums. Both are linear in time; they differ in memory.
Edge cases to test
- Nothing missing. [3, 1, 2, 4] is a full set of 1 to 4, so the answer is [].
- One value everywhere. [4, 4, 4, 4] marks only slot 3, so 1, 2 and 3 are missing.
- A single number. [1] is always complete.
- Gaps at both ends. [2, 2, 3, 3] misses 1 and 4: check the first and last slots too.
Common mistakes
- Using
nums[x − 1]with a value that is already negative, which gives a negative index. - Flipping the sign with
−nums[k], so a value seen twice looks unseen. - Returning the positive slot's index
iinstead of the valuei + 1.
How to talk through it
- 1Clarify. Values are always 1 to n? Does the answer need to be sorted? May I change the input?
- 2Start with a set. Store what you see, then check 1 to n: O(n) time and O(n) space.
- 3Use the value range. Values 1 to n match the n slots, so each value can mark its own slot.
- 4Explain the mark. A negative sign means seen; abs() keeps the original value readable.
- 5Test out loud. Run a case with nothing missing and one with a single repeated value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?