Skip to main content
Back to problems
#362
Medium Algorithms

Design hit counter

Array Binary Search Design Queue Data Stream
69.6% acceptance
Mar 31, 2026
2143
255

No description available.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::VecDeque;

struct HitCounter {
  hits: VecDeque<(i32, i32)>, // (timestamp, count)
  total: i32,
}

impl HitCounter {
  fn new() -> Self {
    HitCounter {
      hits: VecDeque::new(),
      total: 0,
    }
  }

  fn hit(&mut self, timestamp: i32) {
    if let Some(back) = self.hits.back_mut() {
      if back.0 == timestamp {
        back.1 += 1;
        self.total += 1;
        return;
      }
    }
    self.hits.push_back((timestamp, 1));
    self.total += 1;
  }

  fn get_hits(&mut self, timestamp: i32) -> i32 {
    let cutoff = timestamp - 300;
    while let Some(&(t, c)) = self.hits.front() {
      if t <= cutoff {
        self.total -= c;
        self.hits.pop_front();
      } else {
        break;
      }
    }
    self.total
  }
}