Skip to content

Commit 914d94b

Browse files
Refactor : Product of Array Except Self
1 parent a1707ad commit 914d94b

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed
Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
class Solution:
22
def productExceptSelf(self, nums):
3-
ans = []
4-
for i in range(len(nums)):
5-
product = 1
6-
for j in range(len(nums)):
7-
if j != i:
8-
product *= nums[j]
9-
ans.append(product)
10-
return ans
3+
n = len(nums)
4+
answer = [1] * n
5+
left = 1
6+
for i in range(n):
7+
answer[i] = left
8+
left *= nums[i]
9+
right = 1
10+
for i in range(n-1, -1, -1):
11+
answer[i] *= right
12+
right *= nums[i]
13+
return answer

0 commit comments

Comments
 (0)