Remove Duplicates (Sorted)

Easy
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 (Sorted)

Approach

Use a slow pointer to track the position for the next unique element and a fast pointer to scan through the array. When the fast pointer finds a value different from nums[slow], increment slow and copy the new value there.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Two Pointers (Same Direction)

Why It Works

In a sorted array, duplicates are adjacent. The slow pointer only advances when a new unique value is found, naturally compacting unique elements to the front.

Updated Mar 2026