Remove Duplicates from Sorted Array

Updated on 20 June, 2025
Remove Duplicates from Sorted Array header image

Problem Statement

The task involves modifying an integer array, nums, sorted in non-decreasing order, to remove any duplicated values. This operation must be done in-place, ensuring each unique element appears only once while preserving the original relative order. The output will be the count of these unique elements, denoted as k. After modification, the array should position all unique elements at the beginning, followed by any values since their specific values beyond the first k indices are irrelevant for the result. Your goal is to return the value k, which represents the number of unique elements in the array.

A custom judge system checks the integrity of the array alteration. The array, nums, after calling the removeDuplicates function, should present the unique elements in its first k positions, mirroring the sequence they appeared in. Tests will verify this by comparing it against a benchmark array up to the length k, ensuring congruence in order and value.

Examples

Example 1

Input:

nums = [1,1,2]

Output:

2, nums = [1,2,_]

Explanation:

Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2

Input:

nums = [0,0,1,1,1,2,2,3,3,4]

Output:

5, nums = [0,1,2,3,4,_,_,_,_,_]

Explanation:

Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints

  • 1 <= nums.length <= 3 * 104
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.

Approach and Intuition

The problem revolves around the effective management of an array with potential duplicates due to its non-decreasing sorted order, ensuring each unique element is retained once. Here's a logical stepwise breakdown of an approach and the concepts behind it:

  1. Two-pointer Technique:

    • Use two pointer indices, one (i) that traverses the array and another (j) that points to the last confirmed unique element in nums.
    • Begin with the first element, considering it unique by placing j there. Iterate through the array with i.
    • Compare each element nums[i] with nums[j]. If they differ, increment j, update nums[j] to this new unique value.
  2. In-place Update:

    • As each new unique value is found, it is placed immediately after the latest unique value (j++), effectively overwriting any duplicates found earlier.
    • This maintains the order and gathers all unique elements at the beginning of the array.
  3. Return the Count of Uniques (k):

    • After processing, j + 1 (as j is zero-indexed) gives the count of unique elements.
  4. Optimization Understanding:

    • The technique is efficient for space, utilizing O(1) extra space as it works in-place.
    • The complexity is primarily O(n) due to a single pass through nums, making it optimal for large inputs as specified in the constraints.

This approach leverages simple array manipulation techniques to achieve the desired state, aligning with the functional expectations and constraints provided.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int deleteRepeats(vector<int>& elements) {
        int newIndex = 1;
        for (int i = 1; i < elements.size(); i++) {
            if (elements[i - 1] != elements[i]) {
                elements[newIndex] = elements[i];
                newIndex++;
            }
        }
        return newIndex;
    }
};

In this task, you modify the given array elements in place and remove any duplicates, ensuring each element appears only once. The array is sorted, allowing for efficient comparison and removal of duplicates.

  • Begin by initializing newIndex to 1. This variable will track the position for storing unique elements.
  • Use a loop to iterate through the array, starting from the second element.
  • Inside the loop, compare each element with the previous one.
  • If the current element does not match the previous, copy this element to the position pointed by newIndex, and then increment newIndex.
  • Finally, the function returns the value of newIndex, which is the new length of the array containing only unique elements.
java
class Solution {
    public int deleteDuplicates(int[] array) {
        int pos = 1;
        for (int j = 1; j < array.length; j++) {
            if (array[j - 1] != array[j]) {
                array[pos] = array[j];
                pos++;
            }
        }
        return pos;
    }
}

The provided Java solution addresses the problem of removing duplicates from a sorted array. The method deleteDuplicates expects an array of integers as input and returns the length of the array after removing duplicates.

  • Start by initializing an integer pos to 1, which tracks the position in the array where the next unique element should be placed.
  • Iterate through the array starting from the second element (index 1) using a for-loop.
  • Inside the loop, compare each element with its predecessor. If they are different, assign the current element to the array at index pos, and then increment pos.
  • After the loop finishes, pos indicates the length of the array containing unique elements. The method returns this value, denoting the new length of the modified array.

The solution effectively modifies the array in place, ensuring that all unique elements are moved to the start of the array, and returns the count of these unique elements. This approach avoids using additional space for another data structure, making it efficient in terms of both time and space complexity.

c
int eliminateDuplicates(int* array, int length) {
    int newIndex = 1;
    for (int i = 1; i < length; i++) {
        if (array[i - 1] != array[i]) {
            array[newIndex] = array[i];
            newIndex++;
        }
    }
    return newIndex;
}

This solution discusses a function eliminateDuplicates written in C, designed to remove duplicates from a sorted array. The function's signature accepts an integer pointer array which points to the beginning of the sorted array, and an integer length which indicates the size of the array.

  • Start by initializing newIndex to 1. This variable will track the position in the array where the next unique element should be placed.
  • Iterate through the array starting from the second element (index 1, as arrays are zero-indexed). Compare each element with its predecessor.
  • If the current element is different from the one before it (i.e., it's not a duplicate), it's assigned to the position at newIndex in the array, and then newIndex is incremented.
  • Continue this process until all elements of the array have been checked.
  • The function finally returns newIndex, which represents the length of the array after duplicates have been removed. Only the first newIndex elements in the array are unique.

This effectively modifies the array in place, using a minimal amount of extra memory—a key advantage for memory-sensitive applications. The returned value allows easy handling of the resultant array's size externally.

For implementing this solution, ensure the array provided is sorted as this is crucial for the algorithm's correctness. If the array is not sorted, the function will not remove all duplicates correctly.

js
var deduplicate = function (array) {
    let newIndex = 1;
    for (let index = 1; index < array.length; index++) {
        if (array[index - 1] != array[index]) {
            array[newIndex] = array[index];
            newIndex++;
        }
    }
    return newIndex;
};

The provided JavaScript function deduplicate efficiently removes duplicates from a sorted array. This function works by iterating over the array and comparing each element with its predecessor. When it finds elements that are not identical, it copies them to a new position in the array, effectively shifting non-duplicate elements to the front.

Follow these steps to understand the implementation:

  1. Initialize newIndex to 1, which will track the position of the last unique element.
  2. Iterate over the array starting from the second element.
  3. Compare the current element with its previous one.
  4. If they are not the same, move the current element to the position at newIndex, and then increment newIndex by one.
  5. After the loop completes, newIndex holds the count of unique elements. The function returns this count.

The function modifies the array in place and returns the length of the array after duplicates have been removed. This approach ensures that extra space usage is minimized, operating with O(1) additional space complexity and O(n) time complexity, where n is the number of elements in the input array.

python
class Solution:
    def deleteDuplicates(self, numbers: List[int]) -> int:
        length = len(numbers)
        newIndex = 1
        for j in range(1, length):
            if numbers[j - 1] != numbers[j]:
                numbers[newIndex] = numbers[j]
                newIndex += 1
        return newIndex

This solution addresses the problem of removing duplicates from a sorted array in Python. The function deleteDuplicates takes a list of integers (numbers) and returns the new length of the list after removing duplicates.

Follow these steps to understand the implementation:

  1. Retrieve the length of the input list numbers and store it in length.
  2. Initialize newIndex to 1, which will be used to insert unique elements at the correct index.
  3. Iterate over the array from the second element (j starts from 1) to the end:
    • Compare the current element (numbers[j]) with the previous element (numbers[j-1]).
    • If they are not the same, it means the current element is unique:
      • Copy this unique element to the position indicated by newIndex.
      • Increment newIndex to prepare for the next potential unique element.
  4. Return newIndex, which now represents the count of unique elements in the modified list.

By the end of the function execution, the first newIndex elements of numbers contain no duplicates. This efficient approach ensures the original list is modified in place, using O(1) extra space and O(n) time complexity, where n is the number of elements in the list.

Comments

No comments yet.