Given an input array nums our function should return an array output that is the product of all elements in the input array except the current index.
Example
Approach 1
To solve this we can use prefix and postfix method. First we create a result array that is initialized to 1 for the length of the numbers in the input array. To calculate the prefix we’re essentially finding the product sum of all the values that prefix the current index. For instance,
While this solution works we’re using O(n) space since output is not regarded for the space complexity. Therefore, to have an O(1) output we can use the output array to hold the prefix and postfix and find the product. In this logic we do use the appropriate indices to represent the prefix or postfix product of the current index that doesn’t include itself. For instance the prefix product we should expect for index 2 in nums is 1.