leetcode

Get Exclusive Product Array (Non Leetcode)

Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.

Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
      = [120, 60, 40, 30, 24]

You must do this in O(N) without using division.

The idea is to construct two arrays, one calculate from left to right, the other calculate right to left.

Then form something like this (four numbers in the array), then you can multiply the num from each array get the exclusive product array.

{              1,         a[0],    a[0]*a[1],    a[0]*a[1]*a[2],  }
{ a[1]*a[2]*a[3],    a[2]*a[3],         a[3],                 1,  }
public int[] calculateExclusiveProductArray(int[] array) {
        int[] results = new int[array.length];

        int[] products_upper = new int[array.length];
        int num=1;
        for (int i=0; i<array.length; i++) {
            products_upper[i] = num;
            num = num * array[i];
        }

        int[] products_lower = new int[array.length];
        num=1;
        for (int i=array.length-1; i>=0; i--) {
            products_lower[i] = num;
            num = num * array[i];
        }

        for (int i=0; i<array.length; i++) {
            results[i] = products_lower[i]*products_upper[i];
        }

        return results;

    }