Leetcode 283: Move Zeroes

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

If new array is allowed

Two-pointer approach: reader and writer

Core logic

To prevent overwriting

  1. Reader always moves forward, writer sometimes moves forward, thus reader>=writer
  2. We write EVERY non-zero value observed (no exception) Therefore, any non-zero value that is overwritten by the writer was previously read and written too!

Algorithm Steps

Initialization - main loop - termination - post processing

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