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].
Input
Example
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.)
The straightforward solution to this problem is to just take the product of the array and divide it by the excluded value to obtain the product except itself. However, we’re explicitly disallowed from using this method.
The idea behind this problem is to create an alternative method to division. To do so, we can split the array into two sub-arrays with the excluded index as our divider. However, since we only care about the product of the sub-arrays, we can just store their accumulating sum. Then we’ll calculate the product of those two sub arrays and multiply them together.
For example, here’s what it’ll look like visually:
Complexity Explanation
Time complexity is O(N) because we’re iterating through the entire input array.
Since we introduced two new arrays to hold the split sub-arrays, the space complexity is O(2N) or just O(N).
However, we can also achieve the same result without creating two arrays. Instead of tracking the accumulating sum inside an array, we’ll just track the accumulating sum itself by combining all the logic into the same iteration.
Complexity Explanation
Time complexity is the same since the overall method didn’t change.
However, the space complexity is now O(1) because we removed the unnecessary arrays.