0

condition is 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]

    public void duplicateZeros(int[] arr) {
        int length = arr.length;
        for(int i=0;i<length;i++){
            if(arr[i]==0){
              arr[i+1]=arr[i];

            }
        }
        
        
    }
}

error is

java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
  at line 6, Solution.duplicateZeros
  at line 54, __DriverSolution__.__helper__
  at line 84, __Driver__.main

why i am getting this error?

ProgramCOder
  • 89
  • 2
  • 2
  • 10
  • 1
    "_why i am getting this error?_" - Because the value at the last array index is `0` and `if(arr[i]==0)` then you try to access `arr[i+1]`. This is out of bounds of the array, hence the exception. – maloomeister Nov 10 '21 at 07:27
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – maloomeister Nov 10 '21 at 07:27
  • so i can solve this error by incrementing the length? – ProgramCOder Nov 10 '21 at 07:28
  • No, you will not have to increase the size of the array (as you can see by the expected output). The solution consists of _inserting an element into the array, while shifting the following values back, losing the last value each time_. – maloomeister Nov 10 '21 at 07:33
  • could you pls help me to implement the algorithm , i am just knewly , maybe just links for resourses) – ProgramCOder Nov 10 '21 at 07:39
  • https://stackoverflow.com/questions/11638123/how-to-add-an-element-to-array-and-shift-indexes/11638195 – maloomeister Nov 10 '21 at 07:40

2 Answers2

0

Try this.

public static void duplicateZeros(int[] arr) {
    int length = arr.length;
    for (int i = 0; i < length; i++) {
        if (arr[i] == 0) {
            System.arraycopy(arr, i, arr, i + 1, length - i - 1);
            ++i;
        }
    }
}

public static void main(String[] args) {
    int[] a = { 1, 0, 2, 3, 0, 4, 5, 0 };
    duplicateZeros(a);
    System.out.println(Arrays.toString(a));
}

output:

[1, 0, 0, 2, 3, 0, 0, 4]
0

Your solution is wrong, and i+1 will cause an index out of bounds on the last i.

You want some result index, named j here:

     [1,0,2,3,0,4,5,0] 
  i   0 1 2 3 4 5 6 7   ---> for i
  j?  0   1 2   3 4    5 6 7
     [1,  2,3,  4,5,   0,0,0] 
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138