#1348
Tweet Counts Per Frequency
MediumHash TableStringBinary SearchDesignSortingOrdered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal solution, we will use a hash map to store the tweet times and then calculate the counts based on the frequency without nested loops. This significantly reduces the time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Store each tweet's time in a hash map where the key is the tweet name and the value is a list of times.
- 2Step 2: Calculate the interval based on the frequency (minute, hour, day).
- 3Step 3: Iterate through the time range and count the tweets that fall into each interval using a single loop.
solution.py22 lines
1# Full working Python code
2class TweetCounts:
3 def __init__(self):
4 self.tweets = {}
5
6 def recordTweet(self, tweetName, time):
7 if tweetName not in self.tweets:
8 self.tweets[tweetName] = []
9 self.tweets[tweetName].append(time)
10
11 def getTweetCountsPerFrequency(self, freq, tweetName, startTime, endTime):
12 if tweetName not in self.tweets:
13 return []
14 counts = []
15 interval = 60 if freq == "minute" else 3600 if freq == "hour" else 86400
16 num_chunks = (endTime - startTime) // interval + 1
17 counts = [0] * num_chunks
18 for time in self.tweets[tweetName]:
19 if startTime <= time <= endTime:
20 index = (time - startTime) // interval
21 counts[index] += 1
22 return countsℹ
Complexity note: The time complexity is O(n) because we only loop through the tweets once and count them based on their respective intervals.
- 1Using a hash map allows for efficient storage and retrieval of tweet times.
- 2Understanding how to calculate intervals is key to optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.