Remove Duplicates from Sorted Array II - Problem

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result.

Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Input & Output

Example 1 — Multiple Duplicates
$ Input: nums = [1,1,1,2,2,3]
Output: 5
💡 Note: Remove one duplicate '1' to get [1,1,2,2,3]. Return length 5. Final array: [1,1,2,2,3,3] where we only consider first 5 elements.
Example 2 — Some Triples
$ Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7
💡 Note: Remove duplicates to get [0,0,1,1,2,3,3]. Two 0s, two 1s, one 2, two 3s - all ≤ 2 occurrences each.
Example 3 — No Excess Duplicates
$ Input: nums = [1,2,3]
Output: 3
💡 Note: No element appears more than twice, so keep all elements. Return length 3.

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • -104 ≤ nums[i] ≤ 104
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
Remove Duplicates II: Allow At Most 2 DuplicatesInput Array111223RemoveTwo Pointers: Keep elements that differ from 2-back positionResult Array11223Return k = 5 (length of valid portion)
Understanding the Visualization
1
Input
Sorted array [1,1,1,2,2,3] with some elements appearing > 2 times
2
Process
Use two pointers to keep at most 2 of each element
3
Output
Return k=5, first 5 elements are [1,1,2,2,3]
Key Takeaway
🎯 Key Insight: Compare with element 2 positions back to naturally allow exactly 2 duplicates per unique value
Asked in
Microsoft 25 Amazon 20 Facebook 15 Google 12
85.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen