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 5176d01

Browse files
authored
Create Product_of_Array_Except_Self.py
1 parent 60e621f commit 5176d01

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Solution - 1: Time: O(N) and Space: O(N)
2+
class Solution:
3+
def productExceptSelf(self, nums: List[int]) -> List[int]:
4+
pre, suff = [nums[0]], [nums[-1]]
5+
n = len(nums)
6+
# Calculating the Prefix Product
7+
for i in range(1, n):
8+
pre.append(pre[-1] * nums[i])
9+
10+
# Calculating the Suffix Product
11+
for j in range(n-2,-1,-1):
12+
suff.append(suff[-1] * nums[j])
13+
suff.reverse()
14+
15+
ans = [0] * n
16+
ans[0] = suff[1]
17+
for i in range(1, n-1):
18+
ans[i] = pre[i-1] * suff[i+1]
19+
20+
ans[n-1] = pre[n-2]
21+
22+
return ans

0 commit comments

Comments
(0)

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