LeetCode 283. Move Zeroes | Two Pointers Solution in JavaScript

📌 Introduction
In this post, we’ll solve LeetCode 283. Move Zeroes. We’ll cover a two-pointer approach, and analyze the time and space complexities. Code examples will be in JavaScript, with step-by-step explanations.
👉 Original problem link: LeetCode – Move Zeroes
1. Problem Overview
The problem requires us to rearrange an integer array, nums
, by moving all the zeros to the end while keeping the relative order of the non-zero elements. This modification must be done in-place, without creating a new copy of the array.
2. Example
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Explanation: The non-zero elements 1, 3, 12
maintain their original relative order, and the zeros are moved to the end of the array.
3. Approaches
🔹 Optimized Approach
Idea:
Use a two-pointer approach, with one pointer (
start
) tracking the position to place the next non-zero element and the other (end
) iterating through the array.Initialize both
start
andend
pointers to 0.Iterate the
end
pointer from the beginning of the array to the end.If the element at the
end
pointer is not zero, swap it with the element at thestart
pointer and then incrementstart
.Always increment the
end
pointer on each iteration.This process ensures that all non-zero elements are moved to the beginning of the array in their original relative order, with the
start
pointer keeping track of the boundary.
Code (JavaScript):
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let start = 0, end = 0
while(end < nums.length){
if(nums[end] !== 0){
[nums[start],nums[end]] = [nums[end],nums[start]]
start++
}
end++
}
};
Time Complexity = O(N)
Space Complexity = O(1)
4. Key Takeaways
✨ Two-pointers are a classic pattern for solving in-place array manipulation problems.
✨ The "in-place swap" approach is often superior to overwriting values, especially in production code where array elements might be objects with references.
✨ Overwriting can lead to issues with garbage collection and memory, while swapping simply reorders existing elements.
Subscribe to my newsletter
Read articles from Shanks directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shanks
Shanks
Senior Dev trying to crack FAANG | Sharing the grind, growth, and late-night code sessions