-
Notifications
You must be signed in to change notification settings - Fork 0
/
238. Product of Array Except Self.py
49 lines (39 loc) · 1.18 KB
/
238. Product of Array Except Self.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution(object):
# def productExceptSelf(self, nums):
# """
# :type nums: List[int]
# :rtype: List[int]
# """
# n = len(nums)
# # Initialize left and right arrays
# left = [1] * n
# right = [1] * n
# res = [1] * n
# # Populate left array
# for i in range(1, n):
# left[i] = left[i - 1] * nums[i - 1]
# # Populate right array
# for i in range(n - 2, -1, -1):
# right[i] = right[i + 1] * nums[i + 1]
# # Calculate the product excluding self for each element
# for i in range(n):
# res[i] = left[i] * right[i]
# return res
#O(1) space
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Initialize left and right arrays
n = len(nums)
res = [1] * n
# Populate left array
for i in range(1, n):
res[i] = res[i - 1] * nums[i - 1]
# Populate right array
right = 1
for i in range(n - 1, -1, -1):
res[i] = res[i] * right
right *= nums[i]
return res