vamsu
7/25/2018 - 11:39 AM

Replace each element of the array with product of every other element without using division operator

Replace each element of the array with product of every other element without using division operator

import java.util.*;
public class ProductOfEveryOtherElement {
    public static void main(String args[]) {
        ProductOfEveryOtherElement everyOtherElement = new ProductOfEveryOtherElement();
        int[][] input = {
          null,
          {},
          {0},
          {0,1,0},
          {1,2,3,4,5},
          {5,3,4,2,6,8},
          {2, 8, 7, 2, 2, 5, 2, 3, 1, 2, 2}
        };
        for(int i=0; i< input.length; i++) {
            System.out.println("Input: " + Arrays.toString(input[i]) + " Result: " + Arrays.toString(everyOtherElement.product(input[i])));
            System.out.println("Input: " + Arrays.toString(input[i]) + " Result Using Recursion: " + Arrays.toString(everyOtherElement.productUsingRecursion(input[i])));
             
        }
    }
    
    public int[] product(int[] input) {
        if(input == null || input.length < 2) {
            return input;
        }
        int[] left = new int[input.length];
        left[0]=1;
        
        for(int i=1; i<input.length; i++) {
            left[i] = left[i-1] * input[i-1];
        }
        
        int rightSum = 1;
        int[] result = new int[input.length];
        result[input.length-1] = left[input.length-1] * rightSum;
        
        for(int i=input.length-2; i >=0; i--) {
            rightSum *= input[i+1];
            result[i] = left[i] * rightSum;
        }
        
        return result;
    }
    
    public int[] productUsingRecursion(int[] input) {
        if(input == null || input.length < 2) {
            return input;
        }
        int[] cloned = input.clone();
        productUsingRecursion(cloned, 0, 1);
        return cloned;
    }
    
    public int productUsingRecursion(int[] input, int i, int left) {
        if(i == input.length) {
            return 1;
        }
        int cur = input[i];
        int right = productUsingRecursion(input, i+1, left * input[i]);
        input[i] = right * left;
        
        return cur * right;
    }
    
}