Move Zeroes Leetcode


Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.


Input: [0,1,0,3,12]
Output: [1,3,12,0,0]


  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.


This can be done in two ways.

  1. Remember the last zero index, and every time you see a non zero value, swap them.
  2. Start with nonZero - 0, put every non zero element you find in nonZero and increment its value. This basically puts all non zero values in the first nonZero indexes, now copy 0 to all the rest from nonZero to len of nums - 1

Accepted golang code for the second type:

func moveZeroes(nums []int)  {
    nonZero := 0
    for i:=0;i<len(nums);i++{
        if nums[i]!=0{
            nums[nonZero] = nums[i]
    for i:=nonZero;i<len(nums);i++{