Skip to content

Commit d2d2f8d

Browse files
committed
#238. Product of Array Except Self
1 parent 560dd70 commit d2d2f8d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Prefix_Sum/product_except_self.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Given an integer array nums, return an array answer such that answer[i] is equal
2+
# to the product of all the elements of nums except nums[i].
3+
4+
# The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
5+
6+
# You must write an algorithm that runs in O(n) time and without using the division
7+
# operation.
8+
9+
10+
11+
# Example 1:
12+
13+
# Input: nums = [1,2,3,4]
14+
# Output: [24,12,8,6]
15+
# Example 2:
16+
17+
# Input: nums = [-1,1,0,-3,3]
18+
# Output: [0,0,9,0,0]
19+
20+
21+
# Constraints:
22+
23+
# 2 <= nums.length <= 105
24+
# -30 <= nums[i] <= 30
25+
# The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
26+
27+
28+
# Follow up: Can you solve the problem in O(1) extra space complexity? (The output array
29+
# does not count as extra space for space complexity analysis.)
30+
31+
32+
class Solution:
33+
def productExceptSelf(self, nums: List[int]) -> List[int]: # type: ignore
34+
ln = len(nums)
35+
result = [1]*ln
36+
for i in range(1,ln):
37+
result[i] = result[i - 1] * nums[i - 1]
38+
39+
suffix = 1
40+
for i in range(ln-1, -1, -1):
41+
result[i] *= suffix
42+
suffix *= nums[i]
43+
return result

0 commit comments

Comments
 (0)