Lochard avatar

Leetcode - 1089. Duplicate Zeros

lochard

Published: 01 Aug 2023 › Updated: 01 Aug 2023Leetcode - 1089. Duplicate Zeros

Leetcode - 1089. Duplicate Zeros

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

Leave Leetcode - 1089. Duplicate Zeros to:

Written by

Asylum seeker who hopes to be rid of authoritarian and their surveillance.

Read more #programming posts


Best Posts From Lochard

We have not curated any of lochard's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Lochard