LeetCode Problem - Link


Problem

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]


Been a while since I was stuck with this. I was also getting back to my game(Kamikaze Kittens) slowly after a slump and didn't Leetcode much lately.

Tried solving this with a different approach but I wound up on solutions that rarely worked. I had the brute-force solution in my mind but it took a while to get it right, thanks to my colleague L for giving me the push I needed.


Bruteforce Approach

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function (nums) {
    var num_of_zeroes = 0;
    for (var i = 0; i < nums.length; i++) {
        if (nums[i] === 0) {
            num_of_zeroes += 1;
        }
    }
    
    for (var i = 0; i < num_of_zeroes; i++) {
        shiftZero(nums)
    }
};


const shiftZero = (nums) => {
    var temp = null;
    for (var i = 0; i < nums.length - 1; i++) {
        if (nums[i] == 0) {
            temp = nums[i]
            nums[i] = nums[i + 1]
            nums[i + 1] = temp
        }
    }
}