Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator and in O(n).

 

Example:
arr[] = {10, 3, 5, 6, 2}
prod[] = {180, 600, 360, 300, 900}

 

 1     public static int[] selfExcluding(int[] input){
 2         if(input == null || input.length == 0) return null;
 3         int len = input.length;
 4         int[] output = new int[len];
 5         for(int i = 0; i < len; i ++){
 6             output[i] = 1;
 7         }
 8         int left = 1, right = 1;
 9         for(int i = 1; i < input.length; i ++){
10             left *= input[i - 1];
11             output[i] *= left; 
12             right *= input[len - i];
13             output[len - i - 1] *= right;
14         }
15         return output;
16     }