Leetcode #283 Move Zeroes

Leetcode #283 Move Zeroes

Difficulty: Easy

Since we know that the array contains only zeros and non-zeros, we can solve it using the Two-Pointer approach in 2 iterations. Use the second pointer like an anchor which only moves after you have populated the desired values.

First iteration:

  • First pointer find the next non-zero values.
  • Second pointer populates from the start of the array.
  • Once the non-zero value is found, swap in place.
  • Increment the second pointer.

Second iteration:

  • We have the position to populate the remaining zero values
  • Populate remaining position with zeros.

Time complexity: O(n)

Space complexity: O(1)

Link: Move Zeroes

var moveZeroes = function(nums) {
    // Second pointer as anchor
    let idx = 0;
    for(let i =0;i<nums.length;i++){
        // Find non-zero values
        if(nums[i]!=0){
            // Populate the value at second pointer - the anchor position 
            // Increment the second pointer
            nums[idx] = nums[i]
            idx++;
        }
    }

    // Populate the remaining values from anchor position with 0
    for(let i =idx;i<nums.length;i++){
        nums[i] = 0;
    }
};