The key is to write an algorithm in O(n) time without using the division operation. If division operation was allowed, the simplest approach would have been getting the product of every elements in the array, and dividing by ith element.
Initialize a base var as 1. This var will contain the incremental product throughout the array scan
Traverse through the list, append the element i to new arr, update the base var as base * arr[i].
Traverse through the list from backwards, update arr[i] = arr[i] base, then update the base var as `base nums[i]`
Return ans array
def productExceptSelf(self, nums: List[int]) -> List[int]:
ans = []
n = len(nums)
base = 1
# Scan from the left
for i in range(n):
ans.append(base)
base = base * nums[i]
# Scan from the right
base = 1
for i in range(n-1,-1,-1):
ans[i] = ans[i] * base
base = base * nums[i]
return ans
n: length of the array
Time Complexity: O(n) Twice of linear scan through the array
Approach
https://leetcode.com/problems/product-of-array-except-self/
The key is to write an algorithm in
O(n)
time without using the division operation. If division operation was allowed, the simplest approach would have been getting the product of every elements in the array, and dividing by ith element.arr
, update the base var asbase * arr[i]
.base
var as `base nums[i]`n: length of the array
O(n)
Twice of linear scan through the arrayO(n)
answer array