How to replace each element in array with the product of every other elements in Java

1 Answer

0 votes
public class MyClass {
    public static void product_of_every_other_elements(int[] arr) {
        int size = arr.length;
        
        if (size == 0) {
            return;
        }
     
        int[] left = new int[size];
        int[] right = new int[size];
     
        left[0] = 1;
        for (int i = 1; i < size; i++) {
            left[i] = arr[i - 1] * left[i - 1];
        }
      
        right[size - 1] = 1;
        for (int j = size - 2; j >= 0; j--) {
            right[j] = arr[j + 1] * right[j + 1];
        }
      
        for (int i = 0; i < size; i++) {
            arr[i] = left[i] * right[i];
        }
    }
    public static void main(String args[]) {
        int[] array = new int[]{ 1, 2, 3, 4, 5 };

        product_of_every_other_elements(array);
      
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}



 
/*
run:
 
120 60 40 30 24 
 
*/

 



answered Sep 22, 2023 by avibootz
...