Remove Duplicates from Sorted Array

Given a sorted array, remove duplicates in place so each unique value appears once, and return the count of unique values — the first part of the array up to that count holds the result.

EasyRecommendedTwo Pointers
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given a sorted array, remove duplicates in place so each unique value appears once, and return the count of unique values — the first part of the array up to that count holds the result.

Why solve this?

Builds directly on the write-pointer idea from Move Zeroes, but now the decision to advance depends on comparing against the previous kept value rather than checking for a fixed sentinel like 0 — a pattern that reappears constantly once arrays are sorted.

Pattern Recognition

Whenever an array is described as already sorted and the task is to compact it down to only the values that satisfy some 'different from the last kept one' rule, a write pointer that compares against its own most recently written value is enough — no extra memory needed.

Prerequisites

  • Move Zeroes — the same write-pointer-over-array shape, applied to a sorted input.
  • Comfort with sorted-array invariants.

Hints

  1. Because the array is sorted, duplicates of a value are always adjacent — you never need to look further back than the last value you kept.
  2. Keep a write pointer starting at index 0. Advance it — and copy the current value into it — only when the current value differs from nums[write].
  3. The final answer isn't the array itself; it's how far the write pointer got, which tells the caller how many leading slots to trust.

Approach

Since the array is sorted, every run of duplicate values is contiguous, so a value only needs to be compared against the most recently kept value — never the whole prefix. Keep a write pointer `i` starting at 0 (the first element is always kept). Scan the array with a read pointer `j` from index 1: whenever nums[j] differs from nums[i], it's a new unique value, so increment `i` first and then copy nums[j] into nums[i]. Once the scan finishes, the first i + 1 slots of the array hold the unique values in order, so the length to return is i + 1.

Code

Solution.java
class Solution {
    public int removeDuplicates(int[] nums) {
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }
        }
        return i + 1;
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays