Python 8 line solution, O(n) time, O(1) space, super easy to understand


  • 0
    L

    Leave a note if you are interested in the principles behind the problem.
    I'll show how to derive the solution from scratch (which is, the obvious O(n^2) time, O(1) space solution)

    def productExceptSelf(self, nums):
            p,prod=[1]*len(nums),1
            for i in xrange(1,len(nums)):
                p[i]=p[i-1]*nums[i-1]
                
            for i in reversed(xrange(len(nums)-1)):
                prod=nums[i+1]*prod
                p[i]=p[i]*prod
            return p

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.