# 238. Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

# Solution

Approach 1: O(n) time and O(n) space. Two passes -- once from the left, and once from the right. Can save space by using only 1 array, and updating on it.

Approach 2: O(n) time and O(1) space except the output.

# Code (Python)

Approach 1:

    def productExceptSelf(self, nums: List[int]) -> List[int]:
        prod_from_left = []
        for num in nums:
            prod_from_left.append(prod_from_left[-1] * num if prod_from_left else num)
        prod_from_right = 1
        for i in range(len(nums) -  1, -1, -1):
            if i != 0:
                prod_from_left[i] = prod_from_left[i-1] * prod_from_right
                prod_from_right *= nums[i]
            else:
                prod_from_left[i] = prod_from_right
        return prod_from_left

Approach 2:

# Code (C++)

Approach 1:

// O(n) time and O(n) space.
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> res;
        int n = nums.size();
        if (n == 0)
            return res;
        vector<int> left = vector<int>(n, 1);
        vector<int> right = vector<int>(n, 1);
        for (int i = 1; i < n; ++i)
        {
            left[i] *= left[i-1] * nums[i-1];
        }
        for (int i = n - 2; i >= 0; --i)
        {
            right[i] *= right[i+1] * nums[i+1];
        }
        for (int i = 0; i < n; ++i)
        {
            res.push_back(left[i] * right[i]);
        }
        return res;
    }
};

Approach 2:

// O(n) time and O(1) space except the output.
class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> res = vector<int>(n, 1);
        if (n == 0)
            return res;
        for (int i = 0; i < n; ++i)
        {
            if (i - 1 >= 0)
                res[i] *= res[i-1] * nums[i-1];
        }
        int prev = 1;
        for (int i = n - 1; i >= 0; --i)
        {
            if (i + 1 < n)
                res[i] *= prev;
            prev *= nums[i];
        }
        return res;
    }
};