We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Duplicate Zeros

Number: 1168

Difficulty: Easy

Paid? No

Companies: Google, Amazon


Problem Description

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. Modify the array in place without using extra space for another array.


Key Insights

  • The array must be modified in place.
  • Duplicating a zero shifts the rest of the elements; hence, working backwards avoids overwriting unprocessed values.
  • A two pointer approach is optimal: one pointer for iterating the original array and another to build the result from the end.
  • Handle edge cases where duplicating a zero might exceed the bounds of the array.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1) in terms of additional storage.


Solution

The approach begins by calculating the number of zeros that would need to be duplicated if space were unlimited. However, since the array has fixed length, we use these counts to determine the final positions for each element by working backwards. Two pointers are used: one at the end of the original array (considering the potential extra zeros) and one at the actual end of the array. As we iterate backwards, if the element is zero, we write it twice (subject to boundary conditions); otherwise, we simply copy the element. This prevents overwriting data that hasn’t been processed yet.


Code Solutions

# Python solution for Duplicate Zeros

def duplicateZeros(arr):
    n = len(arr)
    # Count the number of zeros that would be duplicated
    zeros_to_dup = 0
    length = n - 1

    # First pass: find the position of the last element after duplicates.
    for i in range(n):
        # If this element is zero, it will be duplicated.
        if arr[i] == 0:
            # Edge case: Check if the zero to be duplicated is exactly at the boundary
            if i == length - zeros_to_dup:
                # Duplicate it only once and reduce the length
                arr[length] = 0
                length -= 1
                break
            zeros_to_dup += 1

    # Second pass: Work backwards from the last element that should be considered.
    last = length - zeros_to_dup
    for i in range(last, -1, -1):
        if arr[i] == 0:
            # Write the duplicated zeros if space allows
            if i + zeros_to_dup < n:
                arr[i + zeros_to_dup] = 0
            zeros_to_dup -= 1
            if i + zeros_to_dup < n:
                arr[i + zeros_to_dup] = 0
        else:
            if i + zeros_to_dup < n:
                arr[i + zeros_to_dup] = arr[i]

# Example usage:
arr = [1,0,2,3,0,4,5,0]
duplicateZeros(arr)
print(arr)  # Output: [1,0,0,2,3,0,0,4]
← Back to All Questions