-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProduct_of_Array_Except_Self.py
More file actions
34 lines (25 loc) · 979 Bytes
/
Product_of_Array_Except_Self.py
File metadata and controls
34 lines (25 loc) · 979 Bytes
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
#Question: Given a list of numbers, multiply each number by all other numbers except itself
#Solution: Traverse right then left while multiplying
#Difficulty: Medium
#Time Complexity: O(n)
#Space Complexity: O(n)
from typing import List
def productExceptSelf(nums: List[int]) -> List[int]:
#Initialize a variable to store the current multiplication, and one to store the result
multiplier, result = 1, [1] * len(nums)
#Loop through forwards
for i, v in enumerate(nums):
#Set the ith index to be the multiplier, and multiply the multiplier by the current number
result[i] *= multiplier
multiplier *= v
#Reset the multiplier
multiplier = 1
#Loop through backwards doing the same thing
for i, v in reversed(list(enumerate(nums))):
result[i] *= multiplier
multiplier *= v
return result
def main():
print(productExceptSelf([1, 2, 3, 4]))
print(productExceptSelf([4,3,2,1,2]))
main()