Knowee
Questions
Features
Study Tools

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Question

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python solution for the problem:

def duplicateZeros(arr):
    i = 0
    while i < len(arr):
        if arr[i] == 0:
            arr.insert(i, 0)
            arr.pop()
            i += 1
        i += 1
    return arr

Here is a step-by-step explanation of the code:

  1. We start by defining a function duplicateZeros that takes an array arr as an argument.

  2. We initialize a counter i to 0. This counter will be used to iterate over the array.

  3. We start a while loop that will continue as long as i is less than the length of the array.

  4. Inside the loop, we check if the current element of the array (i.e., arr[i]) is 0.

  5. If it is, we insert a 0 at the current index i using the insert method. This shifts all elements to the right.

  6. Since the array is of fixed length, we need to remove the last element of the array to maintain the same length. We do this using the pop method.

  7. We then increment i by 1 to skip the next 0 we just inserted.

  8. If the current element is not 0, we simply increment i by 1 to move to the next element.

  9. Finally, we return the modified array.

This problem has been solved

Similar Questions

Write a Java program to remove the duplicate elements of a given array and return the new length of the array.

Given an array Arr of N positive integers. Your task is to find the elements whose value is equal to that of its index value ( Consider 1-based indexing ).

Write a Java program to remove the duplicate elements of a given array and return the new length of the array

Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s

Given a one dimensional array arr, what is the correct way of getting the number of elements in arr is

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.