[LeetCode] Tweet Counts Per Frequency

1348. Tweet Counts Per Frequency

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class TweetCounts {
unordered_map<string, multiset<int>> tweet;
unordered_map<string, int> intervals {{"minute", 60}, {"hour", 3600}, {"day", 86400}};
public:
TweetCounts() {

}

void recordTweet(string tweetName, int time) {
tweet[tweetName].insert(time);
}

vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {
vector<int> res;
int interval = intervals[freq];
int from = startTime;
int to = min(startTime + interval - 1, endTime);
auto fromIt = lower_bound(tweet[tweetName].begin(), tweet[tweetName].end(), from);
auto toIt = upper_bound(tweet[tweetName].begin(), tweet[tweetName].end(), to);
while(to != endTime) {
if(fromIt != end(tweet[tweetName]) && from <= *fromIt && *fromIt <= to) {
res.push_back(std::distance(fromIt, toIt));
fromIt = toIt;
}
else {
res.push_back(0);
}
from += interval;
to = min(from + interval - 1, endTime);
toIt = upper_bound(tweet[tweetName].begin(), tweet[tweetName].end(), to);
}
if(fromIt != end(tweet[tweetName]) && from <= *fromIt && *fromIt <= to) {
res.push_back(std::distance(fromIt, toIt));
fromIt = toIt;
}
else {
res.push_back(0);
}

return res;
}
};

/**
* Your TweetCounts object will be instantiated and called as such:
* TweetCounts* obj = new TweetCounts();
* obj->recordTweet(tweetName,time);
* vector<int> param_2 = obj->getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/04/PS/LeetCode/tweet-counts-per-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.