DSA AnimatorDSA animations
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.

How to solve Remove Duplicates from Sorted Array

LeetCode 26 · Easy · Arrays · Pattern: Two Pointers

Why the obvious approach is slow

Building a new array of unique values uses O(n) extra space. The problem asks you to do it in place.

The key idea

Because the array is sorted, duplicates sit next to each other. Keep a write pointer k, which marks the end of the unique part. A read pointer scans ahead, and copies a value forward only when it differs from the last unique one.

Remember

A slow write pointer and a fast read pointer compact an array in place. In a sorted array, a value is new exactly when it differs from the last kept value.

Run the animation above on your own input, or watch the 1:31 video explanation of Remove Duplicates from Sorted Array with a dry run and Java code.

More Arrays problems