Remove Duplicates from Sorted Array in Java

0 min read 167 words

Say you have an array of primitive integers and you want to remove all duplicates.

You can find out how many non-duplicate integers are in the array with this method:

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

Because we pass the nums array in as a reference, and modify the variable in-place with no additional space, you could just continue using it as is.

Your other option could be to return the nums variable at the end if you wanted the actual duplicates removed out:

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

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags