Move zeroes to the end

Easy TimeO(n) SpaceO(1)

Given an array nums, move every zero to the end in place, with no second array, while the non-zero values keep their relative order exactly. So [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0], with the zeros all together at the back.

Examples

Example 1

Input
nums = [0, 1, 0, 3, 12]
Output
[1,3,12,0,0]
1, 3 and 12 keep that order, and the two zeros follow them.

Example 2

Input
nums = [0, 0, 1]
Output
[1,0,0]
The one non-zero value goes to the front, and both zeros follow it.

The Code

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