Remove Duplicates from Sorted Array

easy array two pointers

Problem

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Two pointers: a write index w marks where the next unique value belongs; a read index r scans the array. Only when the new value differs from the previous kept one do we copy and advance w.

Inputnums = [1, 1, 2, 3, 3, 3, 5]
Output4, nums starts with [1, 2, 3, 5, …]

def remove_duplicates(nums):
    if not nums:
        return 0
    w = 1
    for r in range(1, len(nums)):
        if nums[r] != nums[w - 1]:
            nums[w] = nums[r]
            w += 1
    return w
function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let w = 1;
  for (let r = 1; r < nums.length; r++) {
    if (nums[r] !== nums[w - 1]) {
      nums[w] = nums[r];
      w++;
    }
  }
  return w;
}
class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int w = 1;
        for (int r = 1; r < nums.length; r++) {
            if (nums[r] != nums[w - 1]) {
                nums[w++] = nums[r];
            }
        }
        return w;
    }
}
int removeDuplicates(vector<int>& nums) {
    if (nums.empty()) return 0;
    int w = 1;
    for (int r = 1; r < (int)nums.size(); r++) {
        if (nums[r] != nums[w - 1]) {
            nums[w++] = nums[r];
        }
    }
    return w;
}
Time: O(n) Space: O(1)