Move Zeroes
LeetCode 283 · View on LeetCode
Move all zeroes to the end while maintaining relative order of non-zero elements. Use a write pointer to place non-zero values at the front, then fill the rest with zeroes.
def move_zeroes(nums: list[int]) -> None:
write = 0
for num in nums:
if num != 0:
nums[write] = num
write += 1
for i in range(write, len(nums)):
nums[i] = 0
if __name__ == '__main__':
a = [0, 1, 0, 3, 12]
move_zeroes(a)
print(a) # [1, 3, 12, 0, 0]
b = [0, 0, 1]
move_zeroes(b)
print(b) # [1, 0, 0]
c = [1, 2, 3]
move_zeroes(c)
print(c) # [1, 2, 3]