I wrote this code, it passed initial test cases but it shows run time error when I submitted. I am unable to understand why? Run time error:- Index -1 array out of bounds for length 8
class Solution {
public int[] duplicateZeros(int[] arr)
{
int n=arr.length;
int count=0;
for(int i=0;i<n;i++)
{
if(arr[i]==0)
count=count+1;
}
int loc= n-1;
int p=n-1+count;
if(count==0)
return arr;
for(int i=n-1,j=p;i>=0;i--,j--)
{
if(j<=n && loc>=0)
{
if(arr[i]==0)
{
arr[loc]=0;
arr[loc-1]=0;
loc=loc-2;
}
else
{
arr[loc]=arr[i];
loc=loc-1;
}
}
}
return arr;
} }