- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/product-of-array-except-self
- topics: Array
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.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
size = len(nums)
ans = [1] * size
prefix = 1
suffix = 1
for i in range(size):
ans[i] = suffix
suffix *= nums[i]
for i in range(size-1, -1, -1):
ans[i] *= prefix
prefix *= nums[i]
return ans