AlgoInsight

DSA problem

Remove Duplicates from a Sorted Array

EasyArraysPattern: Two PointersbeginnerFreeAmazonMicrosoft

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: 5
Explanation: The unique elements are [1, 2, 3, 4, 5], so the first 5 slots become that and the new length is 5.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

array

Browse all DSA problems