#1348
Medium Algorithms Tweet counts per frequency
Hash Table String Binary Search Design Sorting Ordered Set
45.9% acceptance
Feb 25, 2026
219
309
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).
For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:
Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]
Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]
Every day (86400-second chunks): [10,10000]
Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).
Design and implement an API to help the company with their analysis.
Implement the TweetCounts class:
TweetCounts() Initializes the TweetCounts object.
void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).
List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.
freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::HashMap;
pub struct TweetCounts {
data: HashMap<String, Vec<i32>>,
}
impl TweetCounts {
pub fn new() -> Self {
TweetCounts { data: HashMap::new() }
}
pub fn record_tweet(&mut self, tweet_name: String, time: i32) {
self.data.entry(tweet_name).or_default().push(time);
}
pub fn get_tweet_counts_per_frequency(
&self,
freq: String,
tweet_name: String,
start_time: i32,
end_time: i32,
) -> Vec<i32> {
let delta = match freq.as_str() {
"minute" => 60,
"hour" => 3600,
"day" => 86400,
_ => 1,
};
let len = ((end_time - start_time) / delta + 1) as usize;
let mut res = vec![0i32; len];
if let Some(times) = self.data.get(&tweet_name) {
for &t in times {
if t >= start_time && t <= end_time {
let bucket = ((t - start_time) / delta) as usize;
res[bucket] += 1;
}
}
}
res
}
}