Move Zeroes in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array to hold some numbers. There are non-zero values as well as zero values. So we have to send all zeros to the right without changing the relative order of other numbers. So if the array is like [0, 1, 5, 0, 3, 8, 0, 0, 9], then the final array will be [1, 5, 3, 8, 9, 0, 0, 0, 0]

To solve this, we will follow these steps −

  • Suppose index = 0
  • for i = 0 to the length of A
    • if A[i] != 0, then
      • A[index] := A[i]
      • index := index + 1
  • for i = index to the length of A
    • A[i] = 0

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def moveZeroes(self, nums):
      """
      :type nums: List[int]
      :rtype: None Do not return anything, modify nums in-place instead.
      """
      insert_index = 0
      for i in range(len(nums)):
         if nums[i] != 0:
            nums[insert_index]=nums[i]
            insert_index+=1
      for i in range(insert_index,len(nums)):
         nums[i]=0
nums = [0,1,5,0,3,8,0,0,9]
ob1 = Solution()
ob1.moveZeroes(nums)
print(nums)

Input

nums = [0,1,5,0,3,8,0,0,9]

Output

[1,5,3,8,9,0,0,0,0]
raja
Published on 09-Jan-2020 08:07:42
Advertisements