DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Move Zeroes LeetCode Python Solution

Prompt states:
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.

Example:
Input: [0, 1, 0, 3, 2]
Output: [1, 3, 2, 0, 0]

We need to look through the given array and keep track of the current number and another number which we will call position.

Starting at position 0, if our number we are iterating is equal to 0, then we want to move on to continue looping until we hit a nonzero.

Then we would swap the two numbers, the position we are keeping track of and the current number. We would repeat this process until the very end of the array.

def moveZeroes(nums):
    pos = 0
    for i in range(len(nums)):
        num = num[i]
        if num != 0:
            nums[pos], nums[i] = nums[pos], nums[i]
            pos += 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)