← Back to DSA Animator
Remove Duplicates from Sorted Array LC #26 Easy Two Pointers
Problem

Given a sorted integer array nums, remove duplicates in-place such that each unique element appears only once. Return the count of unique elements k. The first k elements of nums must hold the unique values.

Example 1
Input: nums = [1,1,2]
Output: k=2, nums=[1,2,_]
Constraints: 1 ≤ nums.length ≤ 3×10⁴  |  −100 ≤ nums[i] ≤ 100  |  Sorted
Try Examples
Custom:
Approach
Slow/Fast Two Pointers
slow marks the next write position. fast scans ahead. When nums[fast] ≠ nums[slow] (new unique value), increment slow and copy. Array is sorted → all duplicates are adjacent.
Array (in-place)
Variables
slow
fast
nums[slow]
nums[fast]
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
slow = 0 (write pointer). Unique count = slow + 1
2
fast scans from 1 to n-1
3
If nums[fast] ≠ nums[slow]: unique! slow++, copy
4
If nums[fast] == nums[slow]: duplicate, skip fast
Time
O(n)
Space
O(1)
Why It Works

Since the array is sorted, duplicates are adjacent. The slow pointer holds the last accepted unique value. Fast advances through duplicates without writing. The moment fast finds a different value, slow advances one step and receives the new unique — overwriting the now-useless duplicate position.