238. Product of Array Except Self
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.
Example 1:
Example 2:
Constraints:
- 2 <= nums.length <= 105
- -30 <= nums[i] <= 30
- The input is generated such that 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.)
Notes
Intuition
The product of all elements except self is equivalent to (product of all elements before i) × (product of all elements after i). We can precompute these prefix and suffix products.
Implementation
Build a prefix array where prefix[i] is the product of all elements before index i. Initialize prefix[0] = 1 (nothing before it), then prefix[i] = nums[i-1] * prefix[i-1]. Similarly, build a suffix array from right to left where suffix[i] is the product of all elements after index i. The answer at each index is prefix[i] * suffix[i].
Edge-cases
The edge indices are handled by initializing prefix and suffix with 1s. No division is needed, so zeros in the array don't cause issues.
- Time: O(n) — three linear passes
- Space: O(n) — prefix and suffix arrays (can be optimized to O(1) by computing on the fly)