As a newbie programmer

Leetcode - 1089. Duplicate Zeros

Leetcode logo

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

Publish0x Publish0x

Reward the author with $0.01 in crypto, and earn yourself as you read!

20% to author / 80% to me.
Rewards are FREE. Publish0x pays them, not you.

Page not displaying correctly?