Problem
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 theTweetCountsobject.void recordTweet(String tweetName, int time)Stores thetweetNameat the recordedtime(in seconds).List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime)Returns a list of integers representing the number of tweets withtweetNamein each time chunk for the given period of time[startTime, endTime](in seconds) and frequencyfreq.freqis one of"minute","hour", or"day"representing a frequency of every minute , hour , or day respectively.
Examples
Example 1
| |
Constraints
0 <= time, startTime, endTime <= 10^90 <= endTime - startTime <= 10^4- There will be at most
104calls in total torecordTweetandgetTweetCountsPerFrequency.
Solution
Method 1 – Hash Map and Binary Search
Intuition
Store tweet times in a map. For each query, use binary search to count tweets in each chunk.
Approach
- Store times for each tweetName in a sorted list.
- For getTweetCountsPerFrequency, determine chunk size, and for each chunk, count tweets using binary search.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(q log q)per query, where q is the number of tweets for the name. - 🧺 Space complexity:
O(n)— For storing all tweet times.