Press "Enter" to skip to content

LeetCode of the day – 283 Move Zeroes (Easy)

Algorithm – Two Pointers

This one was pretty straight forward though I fell right within the average performance. My naive approach was a bit off by not fully understanding the question and jumping right into coding. Rather than looking at the sample input, I designed my solution around a string that needed to be split. Reminder to self to fully read and ensure I understand the question and inputs prior to coding a solution. Time Complexity O(N).

For the base case I’m returning if the array does not include 0’s. I do see there is room for optimization IE: If there is {n} zero’s and we know we have moved the zero to the end we can end execution.

Here is my solution, it could be optimized though this was my accepted solution with good enough performance:

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {

    let left = 0, right = nums.length - 1;

    if (!nums.includes(0)) {
        return;
    }

    while (left <= right) {
        if (left === right) {
            return 
        }

        if (nums[left] === 0 && nums[right] !== 0) {
            nums.splice(left, 1);
            nums.push(0)
        } else if (nums[right] === 0) {
            right--
        } else {
            left++
        }
    }
};
Leave a Reply

Your email address will not be published. Required fields are marked *