A two-pointer approach to move all non-zero elements to the front of an array
read) to read the new number and decide whether it is 0 or not.record) to keep track of the position where the next non-zero element should be placed.read obviously starts from 0.record starts from 0.read proceeds by for loop. record only proceeds when nums[read] is nonzero.record is always less than or equal to read Easy. When read reaches the end of the array.
Easy. Fill the remaining positions in the array (from record to the end) with zeros.
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
nums list first to move all non-zero elements to the beginning of the array which costs $O(n)$ time. At the worst case when the original array only consists of 0s, we will use $O(n)$ time to fill all remaining elements with 0s. Hence, the overall time complexity is $O(2n)$, which is simplified to $O(n)$. However, the total number of operations are still sub-optimal. The total operations (array writes) that the code does is $n$ (Total number of elements).