Friedrich Ewald My Personal Website

Leetcode: Move zeros

The task is as follows: Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. The last note is actually the important part. Without this, it would be easy to just use array splitting in Python and add a zero. This would look similar to this:

if nums[pos] == 0:
  nums = nums[:pos] + nums[pos+1:] + [0]
This obviously overrides nums and the change is no longer in place. The next best solution that I found was to delete the items at position I from the list and then add a zero to the end. It is important to note, that the index needs to be decremented by one in case a 0 is found to account for double 0. The number of steps needs to always be increased.
from typing import List, Optional


class Solution:
  def moveZeroes(self, nums: List[int]) -> None:
    """
    Do not return anything, modify nums in-place instead.
    """
    pos = 0
    steps = 0
    while steps < len(nums):
      if nums[pos] == 0:
        del nums[pos]
        nums.append(0)
        pos -= 1
      pos += 1
      steps += 1


if __name__ == '__main__':
  s = Solution().moveZeroes
  l = [0,1,0,3,12]
  print(s(l), [1,3,12,0,0])
  l = [0]
  print(s(l), [0])
  l = [0,0,1]
  print(s(l), [1,0,0])
Runtime: 189 ms, faster than 84.86% of Python3 online submissions for Move Zeroes. Memory Usage: 15.6 MB, less than 17.32% of Python3 online submissions for Move Zeroes.


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.