AlgoMaster Logo

Remove Duplicates from Sorted Array

Last Updated: February 6, 2026

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Understanding the Problem

At first glance, removing duplicates seems trivial. Just iterate through the array and keep track of unique elements, right? The catch is the in-place requirement. We cannot create a new array to store the results. We must modify the original array and tell the caller how many unique elements exist.

The problem gives us a crucial clue that many overlook: the array is sorted. This means all duplicates are grouped together. In [1, 1, 2, 2, 2, 3], all the 1s are adjacent, all the 2s are adjacent, and so on. We never have to worry about finding a duplicate "later" in the array that we missed earlier.

This sorted property completely changes how we approach the problem. Instead of using a hash set to track seen elements (which would require extra space), we can simply compare adjacent elements. If two adjacent elements are the same, one of them is a duplicate.

The expected return value is k, the count of unique elements. But we also need to physically place those unique elements in the first k positions of the array. The elements beyond position k-1 can be anything since the caller will ignore them.

Approaches

1. Two Pointers Approach

Intuition:

In a sorted array, duplicates always appear next to each other.

This makes it easy to remove duplicates using a two-pointer technique:

  • writePos – points to the position where the next unique element should be placed
  • readPos – scans the array to find the next unique element

Whenever we discover a new unique value, we move it to nums[writePos] and advance writePos.

All unique elements end up at the front of the array. Anything beyond writePos is irrelevant.

Steps:

  1. If the array is empty, return 0 since no elements exist.
  2. Initialize writePos = 0, marking where the next unique element should be placed.
  3. Use readPos to scan from the second element onward.
  4. If nums[readPos] is different from nums[writePos], we found a new unique element.
  • Increment writePos.
  • Copy nums[readPos] to nums[writePos].
  1. Return writePos + 1, the count of unique elements.

Code: