238. Product of Array Except Self
[Medium] “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]."
Note: this one was a real struggle to come up with, but the answer itself is not complex.
Python3:
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
left_array = [1] * length
right_array = [1] * length
res = [1] * length
for i in range(1, length):
left_array[i] = nums[i - 1] * left_array[i - 1]
for i in reversed(range(0, length - 1)):
right_array[i] = nums[i + 1] * right_array[i + 1]
for i in range(length):
res[i] = left_array[i] * right_array[i]
return res