Move Zeroes
Different approaches to solve Leetcode 283 in JavaScript
Today, we’ll tackle a common problem that often arises when working with integer arrays: how to effectively move all 0’s to the end while preserving the order of the non-zero elements. While it may seem like a simple task at first, this problem requires careful consideration of array manipulation techniques and optimization strategies. By the end of this article, you’ll have a better understanding of array manipulation in general.
Problem Statement:
Given an integer array
nums
, move all0
'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.
Approach 1: Two Pointers
Iterate through the array using two pointers, one to track the last non-zero index seen and another to iterate through the array.
For each non-zero element encountered, swap it with the element at the last non-zero index.
This approach avoids the need for an additional array.
// ES6 Arrow Function
const moveZeroes = nums => {
let slowPointer = 0;
for(let i = 0; i < nums.length; i++) {
if(nums[i] !== 0) {
[nums[slowPointer], nums[i]] = [nums[i], nums[slowPointer]];
slowPointer++;
}
}
return nums;
}
Time Complexity: O(N)
Space Complexity: O(1)
Approach 2: Optimized Two-Pointers
Similar to the two-pointer approach, instead of swapping non-zero elements with the last non-zero element, simply replace the last non-zero element with the current non-zero element. This avoids unnecessary swaps and can improve performance.
// ES6 Arrow Function
const moveZeroes = nums => {
let counter = 0;
for(let i = 0; i < nums.length; i++) {
if(nums[i] !== 0) {
nums[counter] = nums[i];
counter++;
}
}
for(let i = counter; i < nums.length; i++) {
nums[i] = 0;
}
return nums;
}
Time Complexity: O(N)
Space Complexity: O(1)
Note: This approach has the same O(n) time complexity as the previous approach, but is faster in practice due to the reduced number of operations needed.
And there you have it guys! I hope this article has provided you with valuable insights and helped you better understand the different approaches to solving this problem. Happy coding!
Problem - Leetcode 283