Intuition
Original Intuition was creating 3 arr
- pre that keeps track of prefix multiplication
- post that keeps track of postfix multiplication
- res that keeps track of results
- compute result using pre times post Further optimization is possible by doing this inplace
- use res as a prefix arr and multiply postfix elements in the second loop
Optimal Solution
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
# compute pre
curr = 1
for i in range(len(nums)):
res[i] = curr
curr *= nums[i]
curr = 1
# compute post
for i in range(len(nums)-1,-1,-1):
res[i] *= curr
curr *= nums[i]
return res
Time Complexity
Time Complexity O(N)
Space Complexity O(N)