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
    }
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.