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
Library Shelf: Remove Excess Book DuplicatesBook ABook ABook ARemoveBook BBook BBook CWriterReader๐Ÿ’ก Key: Compare current book with book 2 positions behind writerIf different titles โ†’ Safe to keep (won't create 3+ duplicates)Result: At most 2 copies of each book! ๐Ÿ“š
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!
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
52.0K Views
High Frequency
~15 min Avg. Time
1.9K 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