Product of Array Except Self

PHOTO EMBED

Fri Mar 15 2024 01:51:35 GMT+0000 (Coordinated Universal Time)

Saved by @playadust

# NC version -- ponder on this more! 
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        res = [1] * (len(nums))

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

# my version 
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        
        pre = [1]+nums[:]+[1]
        for i in range(1, len(pre)-1):
            pre[i] = pre[i-1]*pre[i]
        print(pre)
 
        post = [1]+nums[:]+[1]
        for i in range(len(post)-2, 0, -1):
            post[i] = post[i+1]*post[i]
        print(post)
        
        res = []
        for i in range(1, len(nums)+1):
            res.append(pre[i-1]*post[i+1])
        return res
content_copyCOPY

https://leetcode.com/problems/product-of-array-except-self/description/