The “Remove Duplicates from Sorted List” problem asks us to remove duplicate elements from a sorted array nums
in-place, such that each element appears only once. The goal is to return the length of the array after duplicates have been removed.
Although the array may still contain the original values after the new length, only the first part (up to the returned length) will contain unique values.
Example:
[0,0,1,1,1,2,2,3,3,4]
5
, with the first five elements being [0,1,2,3,4]
This problem teaches one of the most fundamental patterns in array manipulation — the two-pointer technique. It is also highly relevant for real-world tasks such as cleaning up datasets, optimizing storage, or processing sorted inputs efficiently.
Since the input array is sorted, duplicates will always be adjacent. This property allows us to overwrite duplicates as we find them using a slow-runner/fast-runner strategy — often called the two-pointer technique.
j = 1
. This will track the position to place the next unique element.i
from 1 to n - 1
:
nums[i] != nums[i - 1]
, it’s a new unique element.nums[j] = nums[i]
and increment j
.j
elements of nums
are unique. Return j
as the new length.
Input: [1, 1, 2]
j = 1
i = 1
: nums[1] == nums[0]
→ duplicate, skipi = 2
: nums[2] != nums[1]
→ unique, set nums[1] = nums[2]
→ array becomes [1, 2, 2]
Return value: 2
, first 2 elements = [1, 2]
Time Complexity: O(n), where n
is the length of the array.
Space Complexity: O(1), because we modify the array in-place and use only a few extra variables.
The “Remove Duplicates from Sorted List” problem is an essential pattern for working with arrays efficiently. By using the two-pointer approach, we avoid unnecessary shifting or use of additional data structures, allowing us to modify the input directly and save on memory and time.