Skip to content

Instantly share code, notes, and snippets.

@wilfreddesert
Created February 16, 2021 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilfreddesert/bae021a80ee90162932f451f119381a8 to your computer and use it in GitHub Desktop.
Save wilfreddesert/bae021a80ee90162932f451f119381a8 to your computer and use it in GitHub Desktop.
class OnlyProductInteger:
def __init__(self, value):
self._value = value
def __str__(self):
return str(self._value)
def __eq__(self, other):
return self._value == other._value
def __mul__(self, other):
if isinstance(other, int):
other = OnlyProductInteger(other)
return OnlyProductInteger(self._value * other._value)
def __rmul__(self, other):
return self.__mul__(other)
__repr__ = __str__
def product(array: List[OnlyProductInteger]) -> List[OnlyProductInteger]:
"""
Time Complexity: O(n)
Space Complexity: O(n)
>>> product([OnlyProductInteger(1), OnlyProductInteger(2), OnlyProductInteger(3)])
[6, 3, 2]
>>> product([OnlyProductInteger(7), OnlyProductInteger(2), OnlyProductInteger(3)])
[6, 21, 14]
>>> product([OnlyProductInteger(5)])
[1]
>>> product([])
[]
"""
if len(array) <= 1:
return [OnlyProductInteger(1)] * len(array)
result = []
length = len(array)
one = OnlyProductInteger(1)
left = [one] + [None] * (length - 1)
right = [None] * (length - 1) + [one]
for i in range(1, length):
left[i] = OnlyProductInteger(left[i - 1] * array[i - 1])
for j in range(length - 2, -1, -1):
right[j] = OnlyProductInteger(right[j + 1] * array[j + 1])
for l_, r_ in zip(left, right):
result.append(l_ * r_)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment