Leetcode logo

Leetcode - 1089. Duplicate Zeros

By Lochard | As a newbie programmer | 1 Aug 2023


Given a fixed-length integer array arr, 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 and do not return anything.

 

Example 1:

Input: arr = [1,0,2,3,0,4,5,0]

Output: [1,0,0,2,3,0,0,4]

Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: arr = [1,2,3]

Output: [1,2,3]

Explanation: After calling your function, the input array is modified to: [1,2,3]

 

Constraints:

1 <= arr.length <= 104

0 <= arr[i] <= 9

class Solution:
    def duplicateZeros( self, arr: List[int] ) -> None:
        n = len( arr )
        i = n + arr.count( 0 ) - 1
        j = n - 1
        
        while j >= 0:
            if i < n:
                if arr[j] == 0:
                    arr[i] = 0
                    i -= 1
                arr[i] = arr[j]
            elif i == n:
                if arr[j] == 0:
                    i -= 1
                    arr[i] = 0
            else:
                if arr[j] == 0:
                    i -= 1
                    
            i -= 1
            j -= 1

How do you rate this article?

0


Lochard
Lochard

20240228 Arrived in the UK for about 2 week. All my fears persist. Some are even getting worse. https://github.com/locharp/asylum_diary/


As a newbie programmer
As a newbie programmer

Sharing entry level codes. My snippets on GitHub https://github.com/locharp/code-snippets

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.