0238-product-of-array-except-self¶
Try it on leetcode
Description¶
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]
Example 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
- The input is generated such that
answer[i]
is guaranteed to fit in a 32-bit integer.
Follow up: Can you solve the problem in O(1)
extra space complexity? (The output array does not count as extra space for space complexity analysis.)
Solution(Python)¶
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
return self.presum_lessspace(nums)
# Time Complexity: O(n^2)
# Space COmplexity: O(1)
def bruteforce(self, nums: List[int]) -> List[int]:
n = len(nums)
res = [0] * n
for i in range(n):
curEle = 1
for j in range(i):
curEle*=nums[j]
for j in range(i+1, n):
curEle*=nums[j]
res[i] = curEle
return res
# Time Complexity: O(n)
# Space COmplexity: O(n)
def presum(self, nums: List[int]) -> List[int]:
n = len(nums)
presum = [1] * n
postsum = [1] * n
presum[0] = 1
presum[1] = nums[0]
for i in range(2, n):
presum[i] = presum[i-1] * nums[i-1]
postsum[n-1] = 1
postsum[n-2] = nums[n-1]
for i in range(n-2, -1, -1):
postsum[i] = postsum[i+1] * nums[i+1]
res = [1] *n
for i in range(n):
res[i] = presum[i] * postsum[i]
return res
# Time Complexity: O(n)
# Space COmplexity: O(1)
def presum_lessspace(self, nums: List[int]) -> List[int]:
n = len(nums)
res = [0] *n
res[0] = 1
for i in range(1, n):
res[i] = res[i-1] * nums[i-1]
rightMul= 1
for i in range(n-1, -1, -1):
res[i] = res[i] * rightMul
rightMul*=nums[i]
return res