-2
public class Dupzero {
    static int dup =0;
    
    public static void duplicateZeros(int[] arr) {
        //read all the elememts in arrays
    for(int i=0;i<arr.length;i++) {
        if(arr[i]==0) {
            for(int j=arr.length-2;j>=i;j--) {
                arr[j+1]=arr[j];
                
            }
            i=i+1;
        
        }
         
    }
    System.out.println(Arrays.toString(arr));
    }

    public static void main(String[] args) {
        int []arr = {
                1,0,2,3,0,4,5,0 
        };
    duplicateZeros(arr);
    }
}

I wrote this code and i get expected output. Previously i was getting wrong output as i missed the statement i=i+1; .. Can you explain me here in the code what is i=i+1 doing ? is it in the right place ?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243

1 Answers1

0

i = i+1 increments the counter of the outer for-loop by 1. When you copy a 0 to the right you need to ignore that copied 0 value as you continue to step through. Otherwise, you will just fill out the array with 0s.

Is it in the right place? Well, you say its working so it seems to be. Write some tests to verify the expected behavior.

vsfDawg
  • 1,425
  • 1
  • 9
  • 12