DSA problem
Remove Duplicates from a Sorted Array
Given a sorted array of N integers, remove duplicates in-place and return the new length k. The first k elements of the array should contain the unique elements in their original order.
Since the array is sorted, all duplicates are adjacent. Use two pointers: a slow pointer i that tracks the position of the last unique element, and a fast pointer j that scans through the array. When arr[j] != arr[i], you have found a new unique element - increment i and copy arr[j] to arr[i].
This is the classic read-pointer / write-pointer pattern used in stream processing, log compaction, and data deduplication.
Examples
Example 1
Input:
nums = [1, 1, 2, 2, 3, 4, 4, 5]Output:
5Explanation: The unique elements are [1, 2, 3, 4, 5], so the first 5 slots become that and the new length is 5.
Constraints
- 1 <= nums.length <= 10^5
- nums is sorted in non-decreasing order
- -10^9 <= nums[i] <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.