A Simple Solution in JavaScript to the LeetCode ‘Move Zeroes’ Problem
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 that 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 <= 104
-231 <= nums[i] <= 231 – 1
Solution
One approach to solve this problem is to use two pointers. We can initialize a pointer left to the start of the
array and a pointer right to the end of the array. Then, we can iterate through the array with a third pointer i.
array and a pointer right to the end of the array. Then, we can iterate through the array with a third pointer i.
If the element at index i is non-zero, we can swap it with the element at index left, and increment left. If the
element at index i is zero, we can skip it and increment i. Once i reaches right, we can break the loop.
element at index i is zero, we can skip it and increment i. Once i reaches right, we can break the loop.
Here is the implementation in JavaScript:
function moveZeroes(nums) {
let left = 0;
let right = nums.length – 1;
for (let i = 0; i <= right; i++) {
if (nums[i] !== 0) {
[nums[i], nums[left]] = [nums[left], nums[i]];
left++;
}
}
return nums;
}
This solution has a time complexity of O(n) and a space complexity of O(1), as it only uses constant extra space.
Test
We can test the function with the following code:
console.log(moveZeroes([0,1,0,3,12])); // [1,3,12,0,0]
console.log(moveZeroes([1,2,3,4,5])); // [1,2,3,4,5]
console.log(moveZeroes([0,0,0,0,1])); // [1,0,0,0,0]
console.log(moveZeroes([1,0,0,0,0])); // [1,0,0,0,0]
I hope this helps! Let me know if you have any questions.