Product of Array Except Self

Problem: Product of Array Except Self

For an array A, the product-except-self of the k-th element can be calculated as the product through A[1] to A[k-1] times the product through A[k+1] to A[n]. Thus we can divide our method into two part, one is calculating the former part forward, the other one calculating the latter part backward.

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        prod = 1
        res = [1] * len(nums)

        for i in xrange(1, len(nums)):
            prod *= nums[i-1]
            res[i] *= prod

        prod = 1
        for i in xrange(len(nums)-2, -1, -1):
            prod *= nums[i+1]
            res[i] *= prod

        return res

results matching ""

    No results matching ""