Product of Array Except Self

problem [https://leetcode.com/problems/product-of-array-except-self/ 238. Product of Array Except Self].

Problem description
Given an integer array, return an array   such that   is equal to the product of all the elements of   except.

The product of any prefix or suffix of  is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in  time and without using the division operation.


 * Example 1
 * Input: nums = [1,2,3,4]
 * Output: [24,12,8,6]


 * Example 2
 * Input: nums = [-1,1,0,-3,3]
 * Output: [0,0,9,0,0]


 * Constraints
 * The product of any prefix or suffix of  is guaranteed to fit in a 32-bit integer.
 * The product of any prefix or suffix of  is guaranteed to fit in a 32-bit integer.
 * The product of any prefix or suffix of  is guaranteed to fit in a 32-bit integer.


 * Follow up
 * Can you solve the problem in  extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Analysis
The analysis will directly address the approach to solve the problem in O(1) extra space complexity.

Since we are not allowed to use the division operation, the idea of computing cumulative products comes to mind. To make use of this concept, we should notice that each results consist of left products (product of numbers to the left of the current number) and right products (product of numbers to the right of the current number). Here is an example to illustrate this:


 * Inputs: [3, 4, 5, 6, 7]
 * Red color indicate numbers appended to left products at each position.
 * Blue color indicate numbers appended to right products at each position.

So we can solve this problem with the following steps:
 * 1) Initialize the   array, whose length is the same as the input.
 * 2) Traverse the   from left to right, and put the left cumulative products in the   array.
 * 3) Traverse the   from right to left, and update the   array using the right cumulative products.
 * 4) * Use a  variable to keep track of the right product during each iteration.
 * 5) * After computing the right product at position i, multiply  by   to update.
 * 6) Return.

Complexity analysis

 * Time complexity
 * Since we traversed through the input  once from left to right and once from right to left, and each iteration has constant computation, the total time complexity is O(n).


 * Space complexity
 * Since we only have used the  variable to store the right cumulative product, which is updated during each iteration in the right-to-left phase, the extra space complexity is O(1).