Tweet Counts Per Frequency — LeetCode 1348 Python Solution
- Problem
- #1348
- Pattern
- Binary Search
- Reading time
- 5 min
- Source
- leetcode.com
The 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).
Example
- Input
- ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
- Output
- [null,null,null,null,[2],[2,1],null,[4]]
- Explanation
- TweetCounts tweetCounts = new TweetCounts();
Python solution
class TweetCounts:
def __init__(self):
self.d = {"minute": 60, "hour": 3600, "day": 86400}
self.data = defaultdict(SortedList)
def recordTweet(self, tweetName: str, time: int) -> None:
self.data[tweetName].add(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
f = self.d[freq]
tweets = self.data[tweetName]
t = startTime
ans = []
while t <= endTime:
l = tweets.bisect_left(t)
r = tweets.bisect_left(min(t + f, endTime + 1))
ans.append(r - l)
t += f
return ans
# Your TweetCounts object will be instantiated and called as such:
# obj = TweetCounts()
# obj.recordTweet(tweetName,time)
# param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Binary Search
Halve the search space each step — over an array, or over the answer itself. LeetCode 1348. Tweet Counts Per Frequency is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.
The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1348. Tweet Counts Per Frequency?
- LeetCode 1348. Tweet Counts Per Frequency is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1348. Tweet Counts Per Frequency?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1348. Tweet Counts Per Frequency?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1348. Tweet Counts Per Frequency cover?
- LeetCode 1348. Tweet Counts Per Frequency is tagged Design, Hash Table, String, Binary Search, Ordered Set and Sorting on LeetCode.