Skip to content

Latest commit

 

History

History
37 lines (33 loc) · 1.28 KB

283. Move Zeroes.md

File metadata and controls

37 lines (33 loc) · 1.28 KB

283. Move Zeroes (Easy)

Algorithm 1

  • when right element != 0, swap left and right.
  • All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.
  • All elements between the current and slow pointer are zeroes.
  • move the right pointer everytime, but only move left when swapped since left is the left bounder of 0s.
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        left = right = 0
        while right < len(nums):
            if nums[right]:
                nums[left], nums[right], = nums[right], nums[left]
                left += 1
            right += 1

Algorithm 2

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        lastNonZeroFoundAt = 0
        # If the current element is not 0, then we need to
        # append it just in front of last non 0 element we found. 
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[lastNonZeroFoundAt] = nums[i]
                lastNonZeroFoundAt += 1
        
        # After we have finished processing new elements,
        # all the non-zero elements are already at beginning of array.
        # We just need to fill remaining array with 0's.
        for i in range(lastNonZeroFoundAt, len(nums)):
            nums[i] = 0