AlgoMaster Logo

Remove Duplicates from Sorted Array

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

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: