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]
Input: [0]
Output: [0]
๐ง 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