Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate zero in array by modifying the array in place

Tags:

java

arrays

There is a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. The elements beyond the length of the original array are not written.

We have to modify input array in place and doesn't have to create new array.

So I created that but it is duplicating the zero which is at the end of array and not the previous zeros. Can somebody help me with this?

public static void addPos() {
    int arr[] = { 1, 2, 0, 3, 0, 5, 0, 7, 8 };
    int result[] = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 0) {
            int loc = i;
            for (int j = 0; j < loc; j++) {
                result[j] = arr[j];
                result[loc] = 0;
            }
            for (int j = loc + 1; j < arr.length; j++) {
                result[j] = arr[j - 1];
            }
        }
    }
    for (int k = 0; k < arr.length; k++)
        System.out.println(result[k]);
}

Output

1
2
0
3
0
5
0
0
7
Expected output:
1
2
0
0
3
0
0
5
0
like image 867
Harry Avatar asked Dec 11 '22 00:12

Harry


2 Answers

Every iteration of the loop overwrites the results from the previous iteration, so the end result only shows the results from the last iteration, which duplicates the last 0 is duplicated.

One way to solve this is by iterating backwards "right to left". It simplifies a lot of things. You can get rid of the auxiliary result array. The basic idea is, go backwards in the array, and every time you find a 0, you duplicate it by rewriting the array to the right of the zero.

public static void addPos() {
    int arr[] = {1, 2, 0, 3, 0, 5, 0, 7, 8};

    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == 0) {
            // duplicate it!
            for (int j = arr.length - 1; j > i; j--) {
                arr[j] = arr[j-1];
            }
        }
    }

    for (int k = 0; k < arr.length; k++) {
        System.out.println(arr[k]);
    }
}
like image 103
Joni Avatar answered Jan 12 '23 00:01

Joni


The for loop keeps overwriting the values in result array, hence the result shows only last duplication.You should not be using the result array at all.Keep shipting values in the original array itself.

You can refer to below code.

for(int i=0;i<arr.length-1;i++){
  if(arr[i]==0){
    for(int j=arr.length-1;j>i;j--){
    arr[j]=arr[j-1];
     }
     i++;
   }
   
}
like image 34
serialkiller Avatar answered Jan 12 '23 00:01

serialkiller