Skip to Content

Remove Duplicates from Sorted Array

Home | Coding Interviews | Arrays and Strings | Remove Duplicates from Sorted Array

Given an integer array nums sorted in increasing order, remove the duplicates in place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

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

Posted by Jamie Meyer 25 days ago