Problem Description#
Given an array nums, write a function to move all 0's to the end of the array 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]
Constraints:
1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31 - 1
Approach#
- The simplest approach is to traverse the array and whenever a 0 is encountered, move it to the end of the array. This approach requires creating a new array.
- We can use two pointers and traverse the array from left to right. Whenever a 0 is encountered, we remove it from its current position and place it at the end of the array. We also move the right pointer one step to the left. If a non-zero element is encountered, we simply move the left pointer to the right.
Solution#
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let l = 0, r = nums.length;
while (l < r) {
if (nums[l] === 0) {
nums.push(nums.splice(l, 1));
r--;
} else {
l++;
}
}
};