SDE & MLE Prep

283. Move Zeroes

Problem

Move every 0 in nums to the end, in place, keeping the non-zero values in their original relative order.

Example: [0,1,0,3,12] → [1,3,12,0,0]

Constraints: no copy of the array; follow-up: minimise the number of writes.

Slow pointer k = next slot for a non-zero. Swap each non-zero into k; zeros drift to the end while relative order is kept.

Complexity: O(n) time, O(1) space.

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        k = 0
        for i in range(len(nums)):
            if nums[i]:
                nums[k], nums[i] = nums[i], nums[k]
                k += 1