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 from Sorted Array II INPUT Sorted Array nums: 1 1 1 2 2 3 0 1 2 3 4 5 Each element can appear at most TWICE Third '1' is extra! Two Pointers Needed: i = write position j = read position nums = [1,1,1,2,2,3] ALGORITHM STEPS 1 Initialize i = 2 (write ptr) 2 Compare nums[j] vs nums[i-2] 3 If Different Copy and increment i 4 Return i Length of result Process Visualization: j=2: nums[2]=1, nums[0]=1 Same! Skip (already 2 ones) j=3: nums[3]=2, nums[0]=1 Different! Copy, i=3 j=4: nums[4]=2, nums[1]=1 Different! Copy, i=4 j=5: Copy 3, i=5 FINAL RESULT Modified Array (first k elements): 1 1 2 2 3 First 5 elements are valid Output: k = 5 [OK] Verification: 1 appears 2 times [OK] 2 appears 2 times [OK] 3 appears 1 time [OK] All elements at most twice! Time: O(n) | Space: O(1) In-place modification Key Insight: Compare each element with the element TWO positions behind the write pointer (i-2). If they are the same, we already have two copies, so skip. If different, we can safely write. This works because the array is sorted, so duplicates are always consecutive. TutorialsPoint - Remove Duplicates from Sorted Array II | Optimal Two-Pointer Approach
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