lc.algoro.dev
← Back to problems

Move Zeroes

Easy #283 View Problem ↗ Array • Two Pointers

Intuition

We want to move all zeros to the end of the array while keeping the relative order of non-zero elements.

A naive approach would be to remove zeros and append them at the end, but that may use extra memory or multiple passes. Instead, we can do this in-place by shifting non-zeros forward and filling the rest with zeros.


Approach

Two-Pointer Technique

  1. Use a pointer insertPos to track the position where the next non-zero element should be placed.
  2. Iterate over the array:
  1. After the iteration, fill the rest of the array (insertPos … n-1) with zeros.

Proof of Correctness


Complexity


Code

TypeScript Solution
export function moveZeroes(nums: number[]): void {
  let insertPos = 0;

  for (let i = 0; i < nums.length; i++) {
    if (nums[i] !== 0) {
      nums[insertPos] = nums[i];
      insertPos++;
    }
  }

  while (insertPos < nums.length) {
    nums[insertPos] = 0;
    insertPos++;
  }
}
Python Solution
def moveZeroes(self, nums):
        insertPos = 0

        for i in range(len(nums)):
            if nums[i] != 0:
                nums[insertPos] = nums[i]
                insertPos += 1

        while insertPos < len(nums):
            nums[insertPos] = 0
            insertPos += 1