1348. Tweet Counts Per Frequency LeetCode Solution
In this guide, you will get 1348. Tweet Counts Per Frequency LeetCode Solution with the best time and space complexity. The solution to Tweet Counts Per Frequency problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Tweet Counts Per Frequency solution in C++
- Tweet Counts Per Frequency solution in Java
- Tweet Counts Per Frequency solution in Python
- Additional Resources
Problem Statement of 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.
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.
Example:
Input
[“TweetCounts”,”recordTweet”,”recordTweet”,”recordTweet”,”getTweetCountsPerFrequency”,”getTweetCountsPerFrequency”,”recordTweet”,”getTweetCountsPerFrequency”]
[[],[“tweet3”,0],[“tweet3”,60],[“tweet3”,10],[“minute”,”tweet3″,0,59],[“minute”,”tweet3″,0,60],[“tweet3”,120],[“hour”,”tweet3″,0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet(“tweet3”, 0); // New tweet “tweet3” at time 0
tweetCounts.recordTweet(“tweet3”, 60); // New tweet “tweet3” at time 60
tweetCounts.recordTweet(“tweet3”, 10); // New tweet “tweet3” at time 10
tweetCounts.getTweetCountsPerFrequency(“minute”, “tweet3”, 0, 59); // return [2]; chunk [0,59] had 2 tweets
tweetCounts.getTweetCountsPerFrequency(“minute”, “tweet3”, 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet
tweetCounts.recordTweet(“tweet3”, 120); // New tweet “tweet3” at time 120
tweetCounts.getTweetCountsPerFrequency(“hour”, “tweet3”, 0, 210); // return [4]; chunk [0,210] had 4 tweets
Constraints:
0 <= time, startTime, endTime <= 109
0 <= endTime – startTime <= 104
There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.
Example not found
Constraints:
0 <= time, startTime, endTime <= 109
0 <= endTime – startTime <= 104
There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.
Complexity Analysis
- Time Complexity: O(n\log n), where n = |\texttt{timeCount}| (C++/Java) | O(\frac{\texttt{endTime} – \texttt{startTime}}{\texttt{chunkSize}} \cdot \log |\texttt{times}|)
- Space Complexity: O(|\texttt{recordTweet()}|)
1348. Tweet Counts Per Frequency LeetCode Solution in C++
class TweetCounts {
public:
void recordTweet(string tweetName, int time) {
++tweetNameToTimeCount[tweetName][time];
}
vector<int> getTweetCountsPerFrequency(string freq, string tweetName,
int startTime, int endTime) {
const int chunkSize = freq == "minute" ? 60 : freq == "hour" ? 3600 : 86400;
vector<int> counts((endTime - startTime) / chunkSize + 1);
const map<int, int>& timeCount = tweetNameToTimeCount[tweetName];
const auto lo = timeCount.lower_bound(startTime);
const auto hi = timeCount.upper_bound(endTime);
for (auto it = lo; it != hi; ++it) {
const int index = (it->first - startTime) / chunkSize;
counts[index] += it->second;
}
return counts;
}
private:
unordered_map<string, map<int, int>> tweetNameToTimeCount;
};
/* code provided by PROGIEZ */
1348. Tweet Counts Per Frequency LeetCode Solution in Java
class TweetCounts {
public void recordTweet(String tweetName, int time) {
tweetNameToTimeCount.putIfAbsent(tweetName, new TreeMap<>());
tweetNameToTimeCount.get(tweetName).merge(time, 1, Integer::sum);
}
public List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime,
int endTime) {
final int chunkSize = freq.equals("minute") ? 60 : freq.equals("hour") ? 3600 : 86400;
int[] counts = new int[(endTime - startTime) / chunkSize + 1];
TreeMap<Integer, Integer> timeCount = tweetNameToTimeCount.get(tweetName);
for (Map.Entry<Integer, Integer> entry : timeCount.subMap(startTime, endTime + 1).entrySet()) {
final int index = (entry.getKey() - startTime) / chunkSize;
counts[index] += entry.getValue();
}
return Arrays.stream(counts).boxed().collect(Collectors.toList());
}
private Map<String, TreeMap<Integer, Integer>> tweetNameToTimeCount = new HashMap<>();
}
// code provided by PROGIEZ
1348. Tweet Counts Per Frequency LeetCode Solution in Python
from sortedcontainers import SortedList
class TweetCounts:
def __init__(self):
self.tweetNameToTimes = collections.defaultdict(SortedList)
def recordTweet(self, tweetName: str, time: int) -> None:
self.tweetNameToTimes[tweetName].add(time)
def getTweetCountsPerFrequency(self, freq: str, tweetName: str,
startTime: int, endTime: int) -> list[int]:
counts = []
times = self.tweetNameToTimes[tweetName]
chunk = 60 if freq == 'minute' else 3600 if freq == 'hour' else 86400
# I := startTime of each chunk
for i in range(startTime, endTime + 1, chunk):
j = min(i + chunk, endTime + 1) # EndTime of each chunk
counts.append(bisect_left(times, j) - bisect_left(times, i))
return counts
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.