Remove duplicates from a sorted array

Easy TimeO(n) SpaceO(1)

Given a sorted array nums, remove the duplicates in place so each distinct value appears once, and return how many distinct values there are. The distinct values have to end up at the front, in order; whatever sits past the returned count is ignored, whatever it holds.

Examples

Example 1

Input
nums = [1, 1, 2, 2, 2, 3, 4, 4]
Output
4
The distinct values are 1, 2, 3, 4, and they now sit at the front in that order.

Example 2

Input
nums = [5, 5, 5]
Output
1
One distinct value, so only nums[0] is part of the answer.

The Code

function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let write = 1;
  for (let read = 1; read < nums.length; read++) {
    if (nums[read] !== nums[write - 1]) {
      nums[write] = nums[read];
      write++;
    }
  }
  return write;
}
removeDuplicates([1, 1, 2, 2, 2, 3, 4, 4]);
Done
Step through removeDuplicates([1, 1, 2, 2, 2, 3, 4, 4]) call by call