> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Move Zeroes

Leetcode Problem 283: Move Zeroes

Problem Summary

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Techniques

  • In-place rearrangement
  • Two-pointer technique

Solution

function moveZeroes(nums: number[]): void {
    let firstZero = 0
    let tempElement = Infinity

    for (let current = 0; current < nums.length; current++) {
        tempElement = nums[current]
        nums[current] = 0

        if (tempElement !== 0) {
            nums[firstZero] = tempElement
            firstZero++
        }
    }
}

let nums = [0,1,0,3,12];
moveZeroes(nums)
console.log(nums)