1089. Duplicate zeros

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not return anything from your function.

Example 1: Input: [1,0,2,3,0,4,5,0]Output: null Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] c

  • code wrong answer..
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        count0 = 0
        for v in arr:
            if v == 0:
                count0 += 1
        for i in range(count0):
            if arr[~i] == 0:
                count0 -= 1
        last_index = len(arr) - 1 - count0
        arr[-1] = arr[last_index]
        last_index -= 1
        i = len(arr)-2
        while last_index > -1:
            if arr[last_index] == 0:
                arr[i] = 0
                arr[i-1] = 0
                i -= 2
            else:
                arr[i] = arr[last_index]
                i -= 1
            last_index -= 1
        

  • code brute force
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        i = 0
        while i < len(arr)-1:
            if arr[i] == 0:
                for j in range(len(arr)-i-2):
                    arr[~j] = arr[~j-1]
                arr[i+1] = 0
                i += 1
            i += 1

  • code best
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        zeroes = arr.count(0)
        n = len(arr)
        for i in range(n-1, -1, -1):
            if i + zeroes < n:
                arr[i + zeroes] = arr[i]
            if arr[i] == 0: 
                zeroes -= 1
                if i + zeroes < n:
                    arr[i + zeroes] = 0