Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b91c171

Browse files
committed
added: product of array except self
1 parent dfb67d0 commit b91c171

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# product of array except self | leetcode 238 | https://leetcode.com/problems/product-of-array-except-self/
2+
# save prefixes to result array and apply postfix in reverse
3+
# (since output array doesnt increase space complexity)
4+
5+
class Solution:
6+
def productExceptSelf(self, nums: list[int]) -> list[int]:
7+
result = []
8+
N = len(nums)
9+
10+
# save prefix to result array
11+
product = 1
12+
for i in range(N):
13+
product = nums[i] * product
14+
result.append(product)
15+
16+
# update result array as per postfix
17+
postfix = 1
18+
for i in range(N - 1, 0, -1):
19+
result[i] = result[i - 1] * postfix
20+
postfix = postfix * nums[i]
21+
result[0] = postfix
22+
23+
return result
24+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /