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 f3bd95f

Browse files
committed
Add solution 238 Product of Array Except Self
1 parent af45984 commit f3bd95f

File tree

1 file changed

+23
-0
lines changed
  • prefix-product/238_Product_of_Array_Except_Self

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def product_except_self(nums: list[int]) -> list[int]:
2+
"""
3+
Computes for each element the product of all other elements in the array.
4+
5+
:param nums: Input array of integers. May contain negatives and zeros.
6+
:return: Array where output[i] = product of all elements except nums[i]
7+
"""
8+
9+
length = len(nums)
10+
left_prefix = [1] * length
11+
right_prefix = [1] * length
12+
13+
for index in range(length - 1):
14+
left_prefix[index + 1] *= nums[index] * left_prefix[index]
15+
16+
for index in range(length - 1, 0, -1):
17+
right_prefix[index - 1] *= nums[index] * right_prefix[index]
18+
19+
return [l * r for l, r in zip(left_prefix, right_prefix)]
20+
21+
22+
assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6], 'Test 1 failed'
23+
assert product_except_self([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0], 'Test 2 failed'

0 commit comments

Comments
(0)

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