Remove duplicates from sorted array

Back to index

From the LeetCode problem with the same name. The problem statement is:

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length.

When we are removing elements we want to overwrite the elements at the beginning of the array first. Since the array will have a shorter length than when we started, this way we will not overwrite elements before considering them. To do this we simply use an integer to point at the position we are about to write to next.

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