Move Zeroes easy

Problem Statement

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note: You must do this in-place without making a copy of the array.

Example 1:

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

Example 2:

Input: nums = [0] Output: [0]

Steps

The key idea is to use two pointers:

  1. zeroPointer: This pointer keeps track of the index where the next zero should be placed. It starts at 0.
  2. currentPointer: This pointer iterates through the array.

The algorithm works as follows:

  • Iterate through the array using currentPointer.
  • If nums[currentPointer] is not 0, swap it with nums[zeroPointer], and increment both pointers.
  • If nums[currentPointer] is 0, only increment currentPointer.

This ensures that all non-zero elements are moved to the beginning of the array, and zeros are left at the end.

Explanation

The algorithm cleverly uses swapping to achieve in-place modification without creating a new array. By maintaining zeroPointer, we always know where the next available slot for a zero is. The swapping ensures that the relative order of non-zero elements is preserved.

Code

function moveZeroes(nums: number[]): void {
    let zeroPointer = 0; // Pointer to the next position for a zero
    for (let currentPointer = 0; currentPointer < nums.length; currentPointer++) {
        if (nums[currentPointer] !== 0) {
            // Swap non-zero element with the element at zeroPointer
            [nums[zeroPointer], nums[currentPointer]] = [nums[currentPointer], nums[zeroPointer]];
            zeroPointer++; // Move zeroPointer to the next available spot
        }
    }
};

Complexity

  • Time Complexity: O(n), where n is the length of the array. We iterate through the array once.
  • Space Complexity: O(1). We perform the operation in-place, using only a constant amount of extra space for the pointers.