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,12]

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

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Solution

from typing import List

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

        for i in range(len(nums)):
            if nums[i] != 0:
                nums[nonZeroIndex] = nums[i]
                nonZeroIndex += 1

        for i in range(nonZeroIndex, len(nums)):
            nums[i] = 0

Test Cases

test = Solution()
numList = [0,1,0,2,3]
test.moveZeroes(numList)
assert numList == [1,2,3,0,0], numList

numList = [0,1]
test.moveZeroes(numList)
assert numList == [1,0], numList

numList = [1,2,3,0,0]
test.moveZeroes(numList)
assert numList == [1,2,3,0,0], numList

numList = [1,2,3]
test.moveZeroes(numList)
assert numList == [1,2,3], numList
print('All Passed!')

Big O Analysis

Space Complexity: O(1)

Time Complexity: O(N)