You are given an array nums sorted from smallest to largest. Some values repeat. Remove extra copies in place so that each value shows up at most twice, and keep the values in their original order.
Return k, the number of values that remain. The first k cells of nums must hold them; whatever sits after position k − 1 is ignored. Use only O(1) extra memory: no second array.
Example 1
Input: nums = [3, 3, 3, 3, 5, 8, 8] Output: 5, nums starts [3, 3, 5, 8, 8] Why: two of the four 3s go; 5 and both 8s stay
2 more examples and the constraints
Example 2
Input: nums = [-1, 4, 4, 4, 6, 6, 6] Output: 5, nums starts [-1, 4, 4, 6, 6] Why: one 4 and one 6 are extra
Example 3
Input: nums = [7] Output: 1, nums starts [7] Why: nothing repeats
Constraints
- 1 ≤ length of nums ≤ 30,000
- −10,000 ≤ nums[i] ≤ 10,000
- nums is sorted in non-decreasing order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Shift out each extraO(n²)
- Read and write pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 equal numbers | Verdict |
|---|---|---|---|
| Shift out each extra | O(n²) | Mention it, then move on | |
| Read and write pointers | O(n) | Best; one pass, in place |
n = length of nums.
Edge cases to test
- Fewer than three numbers. [7] or [2, 2] are already fine; return the length.
- All the same. Six 0s keep just two: return 2.
- No repeats. [1, 2, 3, 4] writes every number over itself and returns 4.
- Negative values. The check compares values, not signs: -5 three times keeps two.
Common mistakes
- Comparing with the last read number, nums[i − 2], instead of the kept one, nums[k − 2]; after a skip they differ.
- Comparing with nums[k − 1], which allows only one copy of each value.
- Building a new list and copying back, which breaks the O(1) memory rule.
How to talk through it
- 1Clarify. Is the array always sorted? Does anything past k matter? Must memory be O(1)?
- 2Give the shift idea. Spot a third copy and shift the tail left. Say it is O(n²) in the worst case.
- 3Split read and write. Read every number, write only the keepers. The kept part is sorted, so nums[k − 2] tells you if x is a third copy.
- 4Code the one pass. Keep the first two always, then compare with two slots back in the kept part.
- 5Test out loud. Run a single number, all equal and no repeats before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?