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.
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:
-
We start by defining a function
duplicateZeros
that takes an arrayarr
as an argument. -
We initialize a counter
i
to 0. This counter will be used to iterate over the array. -
We start a while loop that will continue as long as
i
is less than the length of the array. -
Inside the loop, we check if the current element of the array (i.e.,
arr[i]
) is 0. -
If it is, we insert a 0 at the current index
i
using theinsert
method. This shifts all elements to the right. -
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. -
We then increment
i
by 1 to skip the next 0 we just inserted. -
If the current element is not 0, we simply increment
i
by 1 to move to the next element. -
Finally, we return the modified array.
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
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.