Skip to content

Commit cb089da

Browse files
committed
product of array except self solution
1 parent 6fe30d9 commit cb089da

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def productExceptSelf(self, nums: List[int]) -> List[int]:
3+
# answer[i] = product up to i * product from i
4+
5+
n = len(nums)
6+
7+
prefix_product = [1] * n
8+
suffix_product = [1] * n
9+
10+
for i in range(1, n):
11+
prefix_product[i] = prefix_product[i-1] * nums[i-1]
12+
13+
for i in range(n - 2, -1, -1):
14+
suffix_product[i] = suffix_product[i + 1] * nums[i + 1]
15+
16+
answer = [1] * n
17+
for i in range(n):
18+
answer[i] = prefix_product[i] * suffix_product[i]
19+
20+
return answer
21+
22+
# Time complexity: O(n)
23+
# Space complexity: O(n)

0 commit comments

Comments
 (0)