Description: Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Code:

def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        write = 0  # Position to write the next non-zero
        
        # Step 1: Move non-zeros forward
        for read in range(len(nums)):
            if nums[read] != 0:
                nums[write] = nums[read]
                write += 1

        # Step 2: Fill remaining positions with 0
        for i in range(write, len(nums)):
            nums[i] = 0

Efficiency:

Time Complexity: O(n)

Space Complexity: O(1), in-place

Test:

nums = [0,1,0,3,12]
moveZeroes(nums)
print(nums)#[1,3,12,0,0]

nums = [0]
moveZeroes(nums)
print(nums)#[0]