My simple python solution with two pointers

  • 3

    keep 2 pointers, the first pointer marks the last non-zero position. We iterate the current pointer, and we would swap all the non-zero element to the later position of first pointer


    class Solution(object):
        def moveZeroes(self, nums):
            start, cur = -1, 0
            while cur < len(nums):
                if not nums[cur] == 0:
                    start += 1
                    nums[cur], nums[start] = nums[start], nums[cur]
                cur += 1

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.