Remove Duplicates from Sorted Array II - Problem
You're given a sorted integer array and need to clean it up by removing excess duplicates, but here's the twist: each unique element can appear at most twice!
๐ฏ Your Mission:
โข Remove duplicates in-place so no element appears more than 2 times
โข Maintain the original relative order
โข Use O(1) extra space - no additional arrays allowed
โข Return the length k of the cleaned array
Example: [1,1,1,2,2,3] becomes [1,1,2,2,3] with length 5
The array is already sorted, which is your biggest advantage! Can you leverage this property to solve it efficiently with a two-pointer approach?
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,1,1,2,2,3]
โบ
Output:
k = 5, nums = [1,1,2,2,3,_]
๐ก Note:
Remove one occurrence of 1. The first 5 elements become [1,1,2,2,3], each appearing at most twice.
example_2.py โ Multiple Duplicates
$
Input:
nums = [0,0,1,1,1,1,2,3,3]
โบ
Output:
k = 7, nums = [0,0,1,1,2,3,3]
๐ก Note:
Remove two occurrences of 1. Result has each element appearing at most twice.
example_3.py โ No Removal Needed
$
Input:
nums = [1,2,3]
โบ
Output:
k = 3, nums = [1,2,3]
๐ก Note:
All elements already appear at most twice, so no removal needed.
Constraints
- 1 โค nums.length โค 3 ร 104
- -104 โค nums[i] โค 104
- nums is sorted in non-decreasing order
Visualization
Tap to expand
Understanding the Visualization
1
Setup Two Bookmarks
Place a 'reader' bookmark to scan all books and a 'writer' bookmark at position 2
2
Check Rule
For each book, check if it's the same as the book 2 positions behind the writer
3
Make Decision
If different, it's safe to keep - move book to writer position and advance writer
4
Continue Scanning
Reader always advances, writer only advances when keeping a book
Key Takeaway
๐ฏ Key Insight: In a sorted array, comparing with the element 2 positions behind ensures we never place a 3rd duplicate consecutively!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code