I'm currently working on a coding challenge from leetcode.com using JavaScript. I'm relatively new to algorithms and seem to be struggling with getting my initial submission accepted.
The task at hand is as follows:
Given an array nums
, the goal is to write a function that shifts all zeros to the end of the array while maintaining the order of non-zero elements.
For instance, for nums = [0, 1, 0, 3, 12]
, the expected output after applying the function should be [1, 3, 12, 0, 0]
.
Note: The transformation needs to be done in-place without creating duplicates of the original array. Efficiency matters; minimize the total number of operations required.
Now, here's the code snippet I've come up with:
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
var i, temp;
for (i = 0; i < nums.length-1; i++) {
if(nums[i] === 0) {
temp = nums.splice(i, 1);
nums.push(temp[0]);
}
}
return null;
};
The instructions provided above this code segment led me to believe that no explicit return statement was needed. However, the platform's validation process doesn't seem to agree with that notion, so I resorted to returning null...
Upon inspecting the modified nums
array through console logging post-execution, I can confirm that it aligns with the desired result [1, 3, 12, 0, 0]
. Yet, my solution continues to face rejection. I'd greatly appreciate any insights into what potential mistakes I might be making here so that I can rectify them.
I acknowledge the possibility of redundancy in my query. While I did stumble upon similar discussions regarding C and Java solutions, I couldn't find one specifically addressing JS.