Remove Duplicates from Sorted Array II

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Remove Duplicates from Sorted Array II

Approach

Use a slow pointer starting at index 2. The fast pointer scans from index 2 onward. Compare nums[fast] with nums[slow - 2]: if they differ, the element is safe to keep (at most 2 copies), so copy it to slow and advance slow.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Two Pointers (Same Direction)

Why It Works

Comparing with nums[slow - 2] ensures at most two copies of any value survive. If nums[fast] equals nums[slow - 2], there are already two copies in the valid region, so it must be skipped.

Updated Feb 2026