python one liner with dictionary, O(1) hit, O(n) getHits, scalable

  • 0

    Store hits for each second in dictionary, go through the dictionary to count hits.
    Huge number of hits in the same second will not make the dictionary bigger.
    The size of the dictionary only grows when hits come at a different second, so I think it is quite scalable.

    class HitCounter(object):
        def __init__(self):
            self.hits = {}
        def hit(self, timestamp):
            self.hits[timestamp] = self.hits.get(timestamp, 0) + 1
        def getHits(self, timestamp):
            return sum([self.hits[k] for k in self.hits if 0 <= timestamp-k < 300])

  • 0

    You should count the sum within the range on the fly.
    You should decrease the container whenever you can.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.