Move Zeroes Leetcode Python Solution

Question

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.

Python Solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i=0
        num_zeros = 0
        while i<len(nums):
            #print(i)
            if i<=len(nums)-num_zeros:
                if nums[i]==0:
                    nums.pop(i)
                    nums.append(0)
                    num_zeros+=1
                else:
                    i+=1
            else:
                break

Cracking the Coding Interview: 189 Programming Questions and Solutions

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.