Leetcode 283: Move Zeroes

A two-pointer approach to move all non-zero elements to the front of an array

Two-pointer approach

Initialization

Main loop

Terminination

Easy. When read reaches the end of the array.

Post processing

Easy. Fill the remaining positions in the array (from record to the end) with zeros.

Caveats

My solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        record = 0
        for read in range(len(nums)):
            if nums[read] != 0:
                nums[record] = nums[read]
                record += 1
        for i in range(record, len(nums)):
            nums[i] = 0

Complexity Analysis

References