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.
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Input: nums = [0]
Output: [0]
Follow up: Could you minimize the total number of operations done?
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
readingPointer = 0;
for nonZeroPointer in range(0, len(nums)):
if nums[nonZeroPointer] != 0 and nums[readingPointer] == 0:
temp = nums[nonZeroPointer]
nums[nonZeroPointer] = nums[readingPointer]
nums[readingPointer] = temp
readingPointer+=1
if nums[readingPointer] !=0:
readingPointer+=1
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nonZeroPointer = 0
# 첫 번째 단계: 0이 아닌 요소를 앞으로 이동
for i in range(len(nums)):
if nums[i] != 0:
nums[nonZeroPointer] = nums[i]
nonZeroPointer += 1
# 두 번째 단계: 남은 부분을 0으로 채우기
for i in range(nonZeroPointer, len(nums)):
nums[i] = 0
Both solutions have same results

Time Complexity : O(n) as we are traveling the array only once.
Space Complexity : O(1) as we are not using any extra space.