PU Product of Array Except Self

Jan 01, 1970

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

C Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
    int *res = malloc(numsSize * sizeof(int));
    *returnSize = numsSize;
    res[0] = nums[0];
    int i;
    for (i = 1; i < numsSize; i++) res[i] = res[i - 1] * nums[i];
    int prod = 1;
    for (i = numsSize - 1; i > 0; i--) {
        res[i] = res[i - 1] * prod;
        prod *= nums[i];
    }
    res[0] = prod;
    return res;
}

Python Solution:

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = [nums[0]]
        for i in range(1, len(nums)):
            res.append(nums[i] * res[-1])
        post = 1
        for i in range(1, len(nums)):
            res[-i] = res[-i - 1] * post
            post *= nums[-i]
        res[0] = post
        return res

Summary:

  • two arrays, two direction. funny.

LeetCode: 238. Product of Array Except Self