BudiBadu Logo

Remove Duplicates from Sorted Array

Sorting Medium 2 views
Like4

You are given a sorted array of integers. Your task is to remove all duplicate elements so that each value appears only once while maintaining the original sorted order. The function should modify the array in place and return the count of unique elements.

After processing, the array should contain only unique numbers in ascending order at the beginning. The remaining part of the array (beyond the returned count) can contain any values and will not be considered. This means you only need to ensure that the first part of the array holds all unique elements in order.

Imagine you are organizing a list of numbers that were already sorted, but some entries were accidentally repeated. You must carefully remove the extra copies while keeping one instance of each number. It’s similar to cleaning up a roster that contains duplicate names—you don’t want to change the order, only ensure every item is unique. The result should reflect the number of distinct elements that remain.

Return the count of unique elements, not the modified array itself.

If sorting is part of the strategy, do it intentionally as a preprocessing step to simplify downstream logic such as merging, ordering, or comparison. After sorting, keep output semantics precise: preserve expected structure, avoid dropping valid entries, and ensure tied cases still follow deterministic order rules.

Examples

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 - Budibadu
Recommendation Algorithm Flow for Remove Duplicates from Sorted Array - Budibadu

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;
    }
}