-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
72 lines (62 loc) · 2.18 KB
/
Solution.cpp
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <cstddef>
#include <cstdlib>
#include <set>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
/**
* Want to monitor metrics in granularities of minutes, hours or days.
*
* Most straightforward way is to define buckets for each tweet, and for each
* partition. Results in x3 space usage, but allows for constant time retrieval
* of metrics.
*
* I.e., store a map of buckets. Define a getBucket(int) function to determine
* the bucket to place the new tweet in.
* This won't really work though. the period queried is varying.
* Feels like some sort of range queries. Can we optimize it?
* What about storing the prefix sums? Still have to scan through to partition.
*
* Let's stick with the naive way.
*/
class TweetCounts {
private:
static constexpr int minuteSeconds = 60;
static constexpr int hourSeconds = 3600;
static constexpr int daySeconds = 86400;
std::unordered_map<std::string, std::multiset<int>> tweets;
public:
TweetCounts() {}
void recordTweet(std::string tweetName, int time) {
tweets[tweetName].insert(time);
}
std::vector<int> getTweetCountsPerFrequency(std::string_view freq,
std::string tweetName,
int startTime,
int endTime) {
int interval = freq[0] == 'm' ? minuteSeconds
: freq[0] == 'h' ? hourSeconds
: daySeconds;
auto iter = tweets.find(tweetName);
if (iter == tweets.end()) {
return {};
}
std::vector<int> buckets((endTime - startTime) / interval + 1, 0);
const std::multiset<int>& records = iter->second;
for (auto it = records.lower_bound(startTime);
it != records.end() && *it <= endTime; ++it) {
int bucketIdx = (*it - startTime) / interval;
++buckets[bucketIdx];
}
return buckets;
}
};
/**
* 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);
*/