Skip to content
LC-1352 Medium LeetCode

1352. Product of the Last K Numbers

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 63% Topics: Array, Math, Design, Data Stream, Prefix Sum
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  ctor: O(1)
#        add : O(1)
#        get : O(1)
# Space: O(n)

class ProductOfNumbers(object):

    def __init__(self):
        self.__accu = [1]

    def add(self, num):
        """
        :type num: int
        :rtype: None
        """
        if not num:
            self.__accu = [1]
            return
        self.__accu.append(self.__accu[-1]*num)             

    def getProduct(self, k):
        """
        :type k: int
        :rtype: int
        """
        if len(self.__accu) <= k:
            return 0
        return self.__accu[-1] // self.__accu[-1-k]

Solution from kamyu104/LeetCode-Solutions · MIT