Move Zeroes
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Approach:
This problem could easily be implemented by making a copy of the array therefore we'll focus on a more efficient implementation.
We initialize two pointers
i = 0
,j = 0
. Iteratej
overrange(len(nums))
if
nums[j] != 0
, we swapnums[i]
andnums[j]
, and incrementi
by1
.
We can now observe that the loop invariant nums[:i+1] contains all nonzero elements in nums[:j+1]
with relative order preserved. Hence when j
reaches len(nums)-1
, nums[:i+1]
contains all nonzero elements in nums
with relative order preserved.
Time: O(n) Space: O(1)
Last updated
Was this helpful?