Skip to content

Commit 8ade49e

Browse files
committed
add productofarrayexceptself py
1 parent 6aaffd5 commit 8ade49e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#Question: Given a list of numbers, multiply each number by all other numbers except itself
2+
#Solution: Traverse right then left while multiplying
3+
#Difficulty: Medium
4+
#Time Complexity: O(n)
5+
#Space Complexity: O(n)
6+
7+
from typing import List
8+
9+
def productExceptSelf(nums: List[int]) -> List[int]:
10+
#Initialize a variable to store the current multiplication, and one to store the result
11+
multiplier, result = 1, [1] * len(nums)
12+
13+
#Loop through forwards
14+
for i, v in enumerate(nums):
15+
16+
#Set the ith index to be the multiplier, and multiply the multiplier by the current number
17+
result[i] *= multiplier
18+
multiplier *= v
19+
20+
#Reset the multiplier
21+
multiplier = 1
22+
23+
#Loop through backwards doing the same thing
24+
for i, v in reversed(list(enumerate(nums))):
25+
result[i] *= multiplier
26+
multiplier *= v
27+
28+
return result
29+
30+
31+
def main():
32+
print(productExceptSelf([1, 2, 3, 4]))
33+
print(productExceptSelf([4,3,2,1,2]))
34+
main()

0 commit comments

Comments
 (0)