Tweet Counts Per Frequency

Let’s break down the problem:

  1. Storing the Tweets: Every time a tweet is recorded, it needs to be stored against its tweetName and the time of tweet.
  2. Counting the Tweets: Based on the frequency provided, we need to break the time between startTime and endTime into smaller chunks and count the number of tweets in each chunk.

Data Structures

  • Use a dictionary called tweets, where the key is the tweetName and the value is a list of all the tweet times for that tweetName.

Method Implementations

  • recordTweet: Simply append the time to the list of times for that tweetName.
  • getTweetCountsPerFrequency: First determine the size of each chunk based on the given frequency. Then, for the given tweetName, partition the period between startTime and endTime into chunks of the determined size and count the number of tweets in each chunk.

Let’s implement this:

 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
from collections import defaultdict

class TweetCounts:
    def __init__(self):
        # Initialize the dictionary to store tweets.
        self.tweets = defaultdict(list)

    def recordTweet(self, tweetName: str, time: int) -> None:
        # Append the time to the list of times for the tweetName.
        self.tweets[tweetName].append(time)

    def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
        # Determine the size of the chunk based on the frequency.
        if freq == "minute":
            size = 60
        elif freq == "hour":
            size = 3600
        else:
            size = 86400

        # Create a list of zeros for the number of chunks.
        chunks = [0] * (((endTime - startTime) // size) + 1)

        # For each tweet time for the given tweetName, determine its chunk and increase its count.
        for t in self.tweets[tweetName]:
            if startTime <= t <= endTime:
                chunks[(t - startTime) // size] += 1

        return chunks

This design efficiently stores the tweets and provides quick lookup times to count the tweets in each chunk for the given frequency.