Move Zeroes

Easy

Given an integer array nums, move all 0's to the end while maintaining the relative order of the non-zero elements. Do this in-place without making a copy of the array.

Examples

InputOutput
nums = [0,1,0,3,12][1,3,12,0,0]
nums = [0][0]

Python Solution

def move_zeroes(nums: list[int]) -> None:
    write = 0
    for read in range(len(nums)):
        if nums[read] != 0:
            nums[write], nums[read] = nums[read], nums[write]
            write += 1

JavaScript Solution

function moveZeroes(nums) {
  let write = 0;
  for (let read = 0; read < nums.length; read++) {
    if (nums[read] !== 0) {
      [nums[write], nums[read]] = [nums[read], nums[write]];
      write++;
    }
  }
}

Step-by-Step Explanation

  1. Two pointers: write is where the next non-zero goes.
  2. When we see a non-zero, swap with write position and increment write.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

ArrayTwo Pointers

Related Problems

Related Tools

All Problems