DevPath

← All problems

Move Zeroes

Easy arrays · two-pointers

Description

Return the array with all zeroes moved to the end while keeping the relative order of the non-zero values.

Constraints

1 <= n <= 100000

Examples

Input: nums = [0,1,0,3,12]

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

Hints (1)
  • Keep a write index for the next non-zero value.

Solutions

Collect non-zero values, then pad with zeroes. · Time O(n) · Space O(n)

func moveZeroes(nums []int) []int {
    out := make([]int, 0, len(nums))
    for _, n := range nums {
        if n != 0 {
            out = append(out, n)
        }
    }
    for len(out) < len(nums) {
        out = append(out, 0)
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account