Move Zeroes
The other day I tried my hand at LeetCode problem 283: Move Zeroes. The directions were as follows:
Given an array
nums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.Example:
Input:
[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
First, I broke down the steps I could take to create this function.
- Create a placeholder for the current position of the index.
- Iterate through the given numbers. If the element at
nums[i]
is not 0, assign that number to the position of the placeholder. - Iterate through the rest of the remaining indices and assign them to 0.
- Return the modified
nums
array.
Now that I have an idea of my code flow, I check to see for edge cases. If there are none, I can finally code the solution!
function moveZeroes(nums) {
let position = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[position++] = nums[i];
}
}
for (let i = position; i < nums.length; i++) {
nums[i] = 0;
}
return nums
}
Success! The solution was accepted with a runtime of 80 ms — that’s faster than 93.86% of JavaScript online submissions for Move Zeroes. The memory usage, however, was 40.5 MB, which is less than 40.85% of JavaScript online submissions for this problem.
What is a solution you can come up with to improve memory usage? I’d love to know!