Move Zeroes(#283)

Category: Array, Two Pointer

๐Ÿงฉ 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. You must do this in-place without making a copy of the array.

๐Ÿ“š Examples

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

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

Explanation:

Input: [0]

Output: [0]

Explanation:

๐Ÿง  Approach

Approach 1:

Use an extra array to collect non-zero elements, then copy them back to nums followed by zeroes.

โ€ข Iterate through the original array.

โ€ข Push all non-zero elements to a new array.

โ€ข Overwrite the original array with elements from the new array.

โ€ข Fill the rest of the array with zeroes.

Approach 2:

Optimized in-place method using Two Pointers.

โ€ข Initialize two pointers, `first` at 0 and `sec` at 1.

โ€ข If `nums[first]` is 0 and `nums[sec]` is non-zero, swap them.

โ€ข Move both pointers forward.

โ€ข If both are zero, only move `sec`.

โ€ข This keeps non-zero elements at the front and pushes zeroes to the end.

๐Ÿ’ป Code

// Approach 1: Using extra space
var moveZeroes = function (nums) {
  let nonZeroes = [];

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

  let i = 0;
  while (i < nonZeroes.length) {
    nums[i] = nonZeroes[i];
    i++;
  }

  while (i < nums.length) {
    nums[i] = 0;
    i++;
  }

  return nums;
};


// Approach 2: In-place using Two Pointers
var moveZeroes = function (nums) {
  let first = 0;
  let sec = 1;

  while (first < sec && sec < nums.length) {
    if (nums[first] === 0 && nums[sec] !== 0) {
      [nums[first], nums[sec]] = [nums[sec], nums[first]];
      first++;
      sec++;
    } else if (nums[first] === 0 && nums[sec] === 0) {
      sec++;
    } else {
      first++;
      sec++;
    }
  }
};

๐Ÿ“ˆ Complexity

Time: O(n)

Space: O(1) for in-place solution, O(n) for brute force

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources