-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproductofarrayexceptself.py
More file actions
42 lines (34 loc) · 1.3 KB
/
productofarrayexceptself.py
File metadata and controls
42 lines (34 loc) · 1.3 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
33
34
35
36
37
38
39
40
41
42
# #time and space complexity is O(n*n)
# def productexceptself(nums):
# result = []
# for index, _num in enumerate(nums):
# lhs = []
# rhs = []
# if index > 0: #This checks whether there are any elements before the current index.If index == 0, there are no elements before it, so lhs should stay empty.
# lhs = nums[0:index] #element before the index
# if index < len(nums) - 1:
# rhs = nums[index + 1:] #This checks whether there are any elements after the current index. If index == len(nums) - 1, that means we are at the last element, so there's nothing after it.
# lhs.extend(rhs)
# # print(lhs)
# res = 1
# for n in lhs: #This condition is because we want product of all elements in the list
# res *= n
# result.append(res)
# return result
# nums = [1,2,4,6]
# print(productexceptself(nums))
#time complexity O(n)
#space complexity O(1)
# def product_exceptself(nums: list):
# res = [1] * len(nums)
# prefix = 1
# for i in range(len(nums)):
# res[i] = prefix
# prefix *= nums[i]
# postfix = 1
# for i in range(len(nums)-1, -1, -1):
# res[i] = postfix * res[i]
# postfix *= nums[i]
# return res
# nums = [1,2,4,6]
# print(product_exceptself(nums))