Duplicate Zeros in Python

PythonServer Side ProgrammingProgramming

Suppose we have a fixed length array of integers, we have to duplicate each occurrence of zero, shifting the remaining elements to the right side.

Note that elements beyond the length of the original array are not written.

So suppose the array is like [1,0,2,3,0,4,5,0], then after modification it will be [1,0,0,2,3,0,0,4]

To solve this, we will follow these steps −

  • copy arr into another array arr2, set i and j as 0
  • while i < size of arr −
    • if arr2[i] is zero, then
      • arr[i] := 0
      • increase i by 1
      • if i < size of arr, then arr[i] := 0
    • else arr[i] := arr2[j]
    • increase i and j by 1


Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def duplicateZeros(self, arr):
      arr2 = [i for i in arr]
      j = 0
      while i < len(arr):
         if not arr2[j]:
            arr[i] = 0
            if i<len(arr):
               arr[i] = 0
            arr[i] = arr2[j]
      return arr
ob1 = Solution()




Published on 16-Jan-2020 16:57:05