Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Constraints:
answer[i] is guaranteed to fit in a 32-bit integer.Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
The brute force approach is to calculate the product of all elements in the array except the one at the current index. We can achieve this by iterating over each element and using an inner loop to calculate the product of all elements except the current one.
n with all elements set to 1.To improve efficiency, we can use two auxiliary arrays to store the product of all elements to the left and to the right of each index. This way, we can construct the result array by multiplying the prefix and suffix products.
prefix and suffix, both of size n.prefix array such that prefix[i] holds the product of all elements to the left of i.suffix array such that suffix[i] holds the product of all elements to the right of i.prefix and suffix.To optimize our space usage, we can eliminate the suffix array and calculate the right product on the fly while filling up the result array. Compute left products into the output first, then sweep from right to left while maintaining a single variable right that accumulates the product of elements to the right of the current index.
i is (product of elements left of i) × (product of elements right of i).right can supply the right part during a backward pass.right to iterate from the end of the array, updating the result by multiplying with right.right in each iteration as you progress from right to left.Pass 1: Build left products (stored in output)
output[i] = output[i - 1] * nums[i - 1]
Pass 2: Sweep from right, multiply by running right product
output[i] *= right, right *= nums[i]