KatInterview

Sliding Window Hit Counter

Data Structure DesignAuto-graded · 21 test cases
EasyAuto-gradedData Structure Designqueuesliding-windowdata-structure-design

Last updated

Tests ability to design time-windowed event counters with efficient memory management and query performance using sliding-window techniques.

Design an in-memory hit counter that tracks events within a rolling 5-minute time window.

Your task is to implement a function that processes a sequence of operations on a hit counter. The counter supports two operations:

hit(timestamp) – Records an event at the given timestamp (measured in seconds).

getHits(timestamp) – Returns the count of all events that occurred within the 5-minute window ending at timestamp. Specifically, it counts events in the closed interval [timestamp - 299, timestamp].

You are given two parallel lists:

  • operations: a list of operation names, each either "hit" or "getHits"
  • arguments: a list where each element is a single-item list [timestamp]

Return a list of results where:

  • Each "hit" operation produces None
  • Each "getHits" operation produces an integer (the count)
  • Any unrecognized operation raises a ValueError

Assumptions:

  • Timestamps are non-decreasing across all operations (they never go backwards, but consecutive operations may share the same timestamp)
  • You should optimize memory by discarding data that falls outside the 5-minute window
  • Aim for better than O(n) time complexity per query, where n is the total number of hits processed

Constraints

  • 1 <= len(operations) <= 10^5
  • operations[i] is "hit" or "getHits"
  • 0 <= timestamp <= 10^9
  • Timestamps are non-decreasing
  • len(operations) == len(arguments)
  • Each arguments[i] contains exactly one integer

Examples

Example 1

Input: sliding_window_hit_counter(['hit', 'hit', 'hit', 'getHits', 'getHits', 'getHits'], [[1], [2], [3], [4], [300], [301]])

Output: [None, None, None, 3, 3, 2]

Example 2

Input: sliding_window_hit_counter(['hit', 'hit', 'hit', 'hit', 'getHits', 'getHits'], [[100], [100], [100], [399], [399], [400]])

Output: [None, None, None, None, 4, 1]

Example 3

Input: sliding_window_hit_counter(['getHits', 'hit', 'hit', 'getHits'], [[10], [10], [10], [10]])

Output: [0, None, None, 2]

Hints

Hint 1

Think about what happens to old events as time moves forward—do you need to keep them forever?

Hint 2

Group events that happen in the same second together to save space and avoid storing millions of individual timestamps.

Hint 3

Maintain a running total that you update incrementally rather than recalculating the sum on every query.