Move Zeros

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

Solution in go
func moveZeroes(nums []int)  {
    insertPosition := 0

    for _, n := range nums {
        if n != 0 {
            nums[insertPosition] = n
            insertPosition++
        }
    }

    for i := insertPosition; i < len(nums); i++ {
        nums[i] = 0
    }
}
    TheDeveloperCafe © 2022-2024