Remove Duplicates from Sorted Array [Easy]

17 Aug 2026 2 min read
1
The Remove Duplicates from Sorted Array problem requires removing duplicate elements from a sorted array in-place while preserving the relative order of the unique elements.

Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements.

The first k elements of nums should contain the unique elements in their original order. The remaining elements beyond the first k positions are not important.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

nums = [1,1,2]

Output

2, nums = [1,2,_] 

Solution

This solution uses the Two Pointer technique. Since the array is already sorted, duplicate elements appear next to each other.

One pointer tracks the position where the next unique element should be placed, while the other pointer scans the array. Whenever a new unique element is found, it is copied to the next available position.

After the traversal, the first k positions contain all unique elements, where k is the number of unique values.
public int removeDuplicates(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;
}

Complexity

The algorithm traverses the array only once, and each element is processed exactly once, resulting in a time complexity of O(n).

The elements are modified directly within the original array, and only a few variables are used, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion