Visualize

Pattern visualizer

Remove Duplicates from Sorted Array

The key insight: use a slow pointer to mark the position of the last unique element written, and a fast pointer to scan through the array. Since the array is sorted, duplicates appear consecutively. When nums[fast] != nums[slow], we've found a new unique element: advance slow and write nums[fast] there. All elements beyond slow are irrelevant after the process completes. Animated on: Given nums = [1, 1, 2, 2, 3], remove duplicates in-place such that the first k elements are unique. Return k = 3, and the first 3 elements become [1, 2, 3]..

Two Pointers

time O(n)space O(1)step 1 / 6
1
[0]
1
[1]
2
[2]
2
[3]
3
[4]
line 1

slow = 0, fast = 1: initialize the slow pointer at the first element (it's always unique so far) and fast at the second element; we're scanning to find the next unique value.

Pseudocode
1FUNCTION removeDuplicates(nums):
2 IF n = 0: RETURN 0
3 slow = 0
4 FOR fast from 1 to n-1:
5 IF nums[fast] != nums[slow]:
6 slow = slow + 1
7 nums[slow] = nums[fast]

← / → step · space play · Home restart

Where to practice Two Pointers