JunyiCode
4/6/2020 - 3:41 AM

238. Product of Array Except Self

class Solution {
    public int[] productExceptSelf(int[] nums) {
        // Final answer array to be returned
        int[] res   = new int[nums.length];
        if(nums == null || nums.length == 0)    return res;

        // answer[i] contains the product of all the elements to the left
        // Note: for the element at index '0', there are no elements to the left,
        // so the answer[0] would be 1
        res[0] = 1;
        for(int i = 1; i < nums.length; i++) {
            // Simply multiplying it with nums[i - 1] would give the product of all elements to the left of index 'i'
            res[i] = res[i - 1] * nums[i - 1];
        }

        // EndToStart contains the product of all the elements to the right
        // Note: for the element at index 'length - 1', there are no elements to the right, so the R would be 1
        int EndToStart = 1;
        for(int i = nums.length - 1; i >= 0; i--) {
            // For the index 'i', EndToStart would contain the product of all elements to the right. We update EndToStart accordingly
            res[i] = res[i] * EndToStart;
            EndToStart *= nums[i];
        }
        
        return res;
    }
}
/*
extra space
*/

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] left  = new int[nums.length];
        int[] right = new int[nums.length];
        int[] res   = new int[nums.length];
        if(nums == null || nums.length == 0)    return res;
        
        
        
        left[0] = 1;
        for(int i = 1; i < nums.length; i++) {
            left[i] = left[i - 1] * nums[i - 1];
        }

        right[nums.length - 1] = 1;
        for(int i = nums.length - 2; i >= 0; i--) {
            right[i] = right[i + 1] * nums[i + 1];
        }
        
        for(int i = 0; i < nums.length; i++) {
            res[i] = left[i] * right[i];
        }
        
        return res;
    }
}