Move Zeros

Two pointers

Problem

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

For example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:

        i = 0
        j = 0 #pointer position for putting the non-zeroes
        
        while i < len(nums):
            if nums[i] != 0:
                t = nums[j]
                nums[j] = nums[i]
                nums[i] = t
                j+=1
            i+=1
        

Last updated