Skip to content

Instantly share code, notes, and snippets.

@countingtoten
Last active August 18, 2020 03:52
Show Gist options
  • Save countingtoten/ab37ba2fd79579d4189100426df111f1 to your computer and use it in GitHub Desktop.
Save countingtoten/ab37ba2fd79579d4189100426df111f1 to your computer and use it in GitHub Desktop.
Given an array of random integers, move all the zeros in the array to the end of the array. Try to keep this in O(n) time (or better)! From @cassidoo's newsletter https://cassidoo.co/newsletter/
package main
import (
"fmt"
)
func moveZeros(nums []int) {
freeSpot := 0
for i, n := range nums {
if n != 0 {
if i != 0 && nums[i-1] == 0 {
nums[freeSpot] = n
nums[i] = 0
}
freeSpot++
}
}
}
func main() {
a := []int{1, 2, 0, 1, 0, 0, 3, 6}
fmt.Println(a)
moveZeros(a)
fmt.Println(a)
}
@countingtoten
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment