Last active
February 9, 2021 03:37
-
-
Save Obayanju/2430093897696824dafe8abf72facfb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Space comp = O(n) where n = number of numbers | |
class ProductList: | |
def __init__(self): | |
self.prefixProd = [] | |
# Time Comp = O(1) | |
def add(self, n): | |
prefixProd = self.prefixProd | |
if n == 0: | |
self.prefixProd = [] | |
else: | |
prev = 1 if not prefixProd else prefixProd[-1] | |
prefixProd.append(prev * n) | |
# Time Comp O(1) | |
def product(self, m): | |
prefixProd = self.prefixProd | |
size = len(prefixProd) | |
if not prefixProd or m > size: | |
return 0 | |
prevPos, prev = size-1-m, 1 | |
if prevPos > -1: | |
prev = prefixProd[prevPos] | |
return prefixProd[-1]//prev | |
#p = ProductList() | |
#p.add(7) | |
#p.add(0) | |
#p.add(2) | |
#p.add(5) | |
#p.add(4) | |
# print(p.product(100)) # return 0 | |
# print(p.product(3)) # return 40 because 2 * 5 * 4 | |
# print(p.product(4)) # return 0 | |
# p.add(0) | |
# p.add(1) | |
# print(p.product(1)) # return 1 | |
#p.add(2) | |
#p.add(0) | |
#p.add(-5) | |
#p.add(6) | |
#p.add(2) | |
#print(p.product(2)) # return 12 | |
#print(p.product(3)) # return -60 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment