FrontendX
Remove Duplicates from Sorted Array II
medium
Description
AI Assistance
Solution
Test Cases
Test Result
Submissions
Canvas
Remove Duplicates from
Sorted Array II
Given a non-decreasing array of integers, return a new array where each value appears at most twice.
Examples
Example 1
Input:
[1,1,1,2,2,3]
Output:
[1,1,2,2,3]
Example 2
Input:
[0,0,1,1,1,1,2,3,3]
Output:
[0,0,1,1,2,3,3]
Hints
Hint 1
Use a two-pointer technique where one pointer iterates through the array and another tracks the position to place the next valid element.
Hint 2
Maintain a count of the current element's occurrences; if it exceeds two, skip adding it to the result.
Hint 3
Optimize space by modifying the input array in-place instead of creating a new one, ensuring the first `k` elements contain the valid output.
Related Problems
remove-duplicates-from-sorted-array
remove-element
merge-sorted-array
Remove Duplicates from Sorted Array II
Given a non-decreasing array of integers, return a new array where each value appears at most twice.