-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem238.py
More file actions
32 lines (25 loc) · 1.22 KB
/
problem238.py
File metadata and controls
32 lines (25 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:
def productExceptSelf(self, nums):
# The length of the input array
length = len(nums)
# The answer array to be returned
answer = [0]*length
# answer[i] contains the product of all the elements to the left
# Note: for the element at index '0', there are no elements to the left,
# so the answer[0] would be 1
answer[0] = 1
for i in range(1, length):
# answer[i - 1] already contains the product of elements to the left of 'i - 1'
# Simply multiplying it with nums[i - 1] would give the product of all
# elements to the left of index 'i'
answer[i] = nums[i - 1] * answer[i - 1]
# R contains the product of all the elements to the right
# Note: for the element at index 'length - 1', there are no elements to the right,
# so the R would be 1
R = 1;
for i in reversed(range(length)):
# For the index 'i', R would contain the
# product of all elements to the right. We update R accordingly
answer[i] = answer[i] * R
R *= nums[i]
return answer