Leet Code

#5 238. Product of Array Except Self

brian | Published: Jan. 17, 2025, 4:32 p.m. | Updated: July 9, 2025, 11:17 p.m.

Profile Picture

'''
Given an integer array nums, return an array answer such that answer[i] 
is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

 

Example 1:

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

class Solution:
    def solve(self, nums:list):
        output = [1] * len(nums)
       
        
        prefix = 1
        for x in range(len(nums)):
           output[x] = prefix
           prefix*= nums[x]
           print(f'Prefix: {prefix}')

        print(f'Prefix Output: {output}')
        print('-'*30)

        suffix = 1
        for x in range(len(nums) - 1, -1, -1):
            output[x]*= suffix
            suffix*= nums[x] 
            
        print(f'Suffix Output: {output}')
        print('-'*30)


        return output

nums = [1, 2, 3, 4] 
s = Solution()

print(s.solve(nums))



# >> [24, 12, 8, 6]