Code Logo

Remove Duplicates from Sorted Array

Published at05 Jan 2026
Array Manipulation Medium 20 views
Like4

In Remove Duplicates from Sorted Array, you are given an array that is already sorted. Your job is to keep only one copy of each distinct value at the front of the array and return how many unique values remain.

The important advantage is that the array is sorted. Because equal values appear next to each other, you do not need a hash set or nested loops to detect duplicates. You only need to notice when the current number changes from the previous one.

For example, if nums = [1,2,3,4], the answer is 4 because every value is already unique. If nums = [1,1,2], the answer is 2 because the unique values are [1,2]. A larger example like [0,0,1,1,1,2,2,3,3,4] returns 5, because the distinct values are [0,1,2,3,4].

So the task is to compact the sorted array so that each value appears once at the front, then return the count of those unique values.

Example Input & Output

Example 1
Input
nums = [1,2,3,4]
Output
4
Explanation

The array already contains unique elements.

Example 2
Input
nums = [0,0,1,1,1,2,2,3,3,4]
Output
5
Explanation

The unique elements are [0,1,2,3,4].

Example 3
Input
nums = [1,1,2]
Output
2
Explanation

The unique elements are [1,2].

Algorithm Flow

Recommendation Algorithm Flow for Remove Duplicates from Sorted Array

Solution Approach

Remove duplicates in-place from a sorted array so each element appears once. Use two pointers: i tracks the last unique position, j scans ahead. When nums[j] differs from nums[i], advance i and copy nums[j] to nums[i]. Return i+1 as the new length.

function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  var i = 0;
  for (var j = 1; j < nums.length; j++) {
    if (nums[j] !== nums[i]) { i++; nums[i] = nums[j]; }
  }
  return i + 1;
}

The sorted order guarantees duplicates are adjacent. The slow pointer i marks the boundary of deduplicated elements.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
class Solution {
    public int remove_duplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int k = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i-1]) {
                nums[k] = nums[i];
                k++;
            }
        }
        return k;
    }
}