Skip to content

Commit 45b8cf2

Browse files
committed
product of array except self solution
1 parent dbde40d commit 45b8cf2

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Goal: Return an array answer that product of all elements except nums[i].
2+
#
3+
# Approach:
4+
# Use prefix&suffix arrays to store cumulative products
5+
# - prefix: product of elements to the left of i
6+
# - suffix: product of elements to the right of i
7+
# Calculate the result[i] by multipying prefix[i] and suffix[i]
8+
#
9+
# Time Complexity: O(n)
10+
# - We Iterate the array to compute prefix, suffix and result.
11+
# Space Complexity: O(n)
12+
# - We use extra arrays for prefix&suffix.
13+
class Solution:
14+
def productExceptSelf(self, nums: List[int]) -> List[int]:
15+
n = len(nums)
16+
17+
prefix = [1] * n
18+
suffix = [1] * n
19+
result = [1] * n
20+
21+
for i in range(1, n):
22+
prefix[i] = prefix[i-1] * nums[i-1]
23+
24+
for i in range(n-2, -1, -1):
25+
suffix[i] = suffix[i+1] * nums[i+1]
26+
27+
for i in range(len(nums)):
28+
result[i] = prefix[i] * suffix[i]
29+
30+
return result

0 commit comments

Comments
 (0)