SDE & MLE Prep

238. Product of Array Except Self

Problem

Return an array answer where answer[i] is the product of every element of nums except nums[i]. Do it in O(n) without using division.

Example: [1,2,3,4] → [24,12,8,6]

Constraints: 2 ≤ n ≤ 10⁵; every prefix/suffix product fits in a 32-bit int. Follow-up: O(1) extra space (the output doesn't count).

ans[i] = (product of everything left of i) × (product of everything right of i). Fill left products in one pass, then multiply by a running right product in a reverse pass. No division needed.

nums     [ 1,  2,  3,  4]
left     [ 1,  1,  2,  6]     (product before i)
right    [24, 12,  4,  1]     (product after i)
answer   [24, 12,  8,  6]

Complexity: O(n) time, O(1) extra space (output excluded).

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [1] * n
        for i in range(1, n):
            ans[i] = ans[i - 1] * nums[i - 1]
        right = 1
        for i in range(n - 1, -1, -1):
            ans[i] *= right
            right *= nums[i]
        return ans