Hit Counter

medium · sliding window

Implement HitCounter(capacity), where capacity >= 1 is the window length in seconds. hit(timestamp) records one hit and returns None. count(timestamp) returns hits in (timestamp-capacity, timestamp], excluding the left boundary. ALL method timestamps are nonnegative integers and nondecreasing across calls, including count calls; duplicate timestamps are separate hits. Use supplied fake times only, never a real clock. Discard expired hits to bound retained history. Examples (JSON; null means Python None): Input: {"capacity": 3, "operations": [["hit", [0]], ["hit", [1]], ["count", [2]], ["count", [3]]]} Output: [null, null, 2, 1] Input: {"capacity": 5, "operations": [["hit", [1]], ["hit", [1]], ["hit", [1]], ["count", [1]], ["count", [6]]]} Output: [null, null, null, 3, 0]

Starter code

class HitCounter:

    def __init__(self, capacity: int):
        """Implement this operation according to the statement."""
        pass

    def hit(self, timestamp: int) -> None:
        """Implement this operation according to the statement."""
        pass

    def count(self, timestamp: int) -> int:
        """Implement this operation according to the statement."""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. AntyCharacter joke · No posting date

    I asked the hash for one shard. It gave me a lecture on consistency.

  2. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  3. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.