LeetCode 238. Product of Array Except Self

Description

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

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

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Constraint: It’s guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

Note: Please solve it without division and in O(n).

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

Explanation

one pass to get products before the target number, one pass to get products after the target number

Python Solution

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        
        post_products = []
        
        j = 0
        for i in range(len(nums) - 1, -1, -1):

            if i == len(nums) - 1:
                post_products.append(nums[i])       
            else:
                post_products.append(post_products[j - 1] * nums[i])
            j += 1
        
        
        post_products = post_products[::-1]
        
        
        pre_products = []
        
        for i in range(0, len(nums)):
            if i == 0:
                pre_products.append(nums[i])       
            else:
                pre_products.append(pre_products[i - 1] * nums[i])

        
        result = []            
        for i in range(0, len(nums)):         
            if i == 0: 
                result.append(1 * post_products[i + 1])
            elif i == len(nums) - 1: 
                result.append(pre_products[i - 1] * 1)
            else:
                result.append(pre_products[i - 1] * post_products[i + 1])
 
        return result
  • Time complexity: O(N).
  • Space complexity: O(N).

One Thought to “LeetCode 238. Product of Array Except Self”

Leave a Reply

Your email address will not be published. Required fields are marked *