Product of Array Except Self

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]. Tags: Array

Try It!

Discussion

Video

Solution

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

        p = 1
        for i in range(len(nums)):
            ans[i] *= p
            p *= nums[i]
        
        p = 1
        for i in range(len(nums) - 1, -1, -1):
            ans[i] *= p
            p *= nums[i]
        
        return ans