We use a slow pointer to track where the next non-zero element should be placed and a fast pointer to find the next non-zero element.
l = 0.- For
rfrom 0 tolen(nums)-1:- If
nums[r] != 0:- Swap
nums[l]andnums[r]. l += 1.
- Swap
- If
- The remaining elements from
lto end are already zeroes (or will be swapped into place).
- Time Complexity: O(N).
- Space Complexity: O(1).
def move_zeroes(nums):
l = 0
for r in range(len(nums)):
if nums[r] != 0:
nums[l], nums[r] = nums[r], nums[l]
l += 1