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]
  

Leetcode Qn :
   
  
public class Solution {
    public void DuplicateZeros(int[] arr) {
        int zerosCount = 0;
        int length = arr.Length;

        // Count the number of zeros in the original array
        foreach (int num in arr)
        {
            if (num == 0)
                zerosCount++;
        }

        for (int i = length - 1; i >= 0; i--)
        {
            if (i + zerosCount < length)
                arr[i + zerosCount] = arr[i];

            if (arr[i] == 0)
            {
                zerosCount--;

                if (i + zerosCount < length)
                    arr[i + zerosCount] = 0;
            }
        }
    }
}
    

Comments