Product of Array Except Itself (Leetcode 238) (DCP 2)

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

Division Method

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        ans=[]
        productwithzero=1
        productwithoutzero=1
        zerocount=0
        for i in nums:
            if(i!=0):
                productwithoutzero=productwithoutzero*i
            else:
                zerocount+=1
            productwithzero=productwithzero*i
        if(zerocount>1):
            return [0]*(len(nums))
        ans=[productwithzero]*(len(nums))
        for i in range(len(nums)):
            if(nums[i]==0):
                ans[i]=productwithoutzero
            else:
                ans[i]=productwithzero//nums[i]
        return ans        

Optimised Approach

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        
        n=len(nums)
        ans=[]
        p=1
        for i in nums:
            p=p*i
            ans.append(p)
        
        p=1
        for i in range(n-1,-1,-1):        
            if(i==n-1):
                ans[i]=ans[i-1]
            elif(i==0):
                ans[i]=p
            else:
                ans[i]=ans[i-1]*p
            p=p*nums[i]
        return ans

Last updated