Skip to main content

Tweet Counts Per Frequency - Solution & Explanation

MediumHash TableBinary SearchDesignSorting9 min readAsked at: Microsoft, Google, Intercom +1
Practice this problem

Problem Statement

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<Integer> 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.

Approach Overview

Problem Overview: Design a data structure that records tweet timestamps and returns how many tweets occurred in each time bucket (minute, hour, or day) within a given range. The main challenge is efficiently storing timestamps and answering repeated range queries.

Approach 1: Brute Force with Unsorted List (O(n) query, O(1) insert)

Store every timestamp for a tweet in a plain list inside a hash table keyed by tweet name. When getTweetCountsPerFrequency is called, iterate through all stored timestamps and count how many fall into each interval bucket. This approach works because insertion is trivial, but every query scans the entire list. Time complexity is O(n) per query and space complexity is O(n). It works for small inputs but becomes slow when tweets accumulate.

Approach 2: Sorted List with Binary Search (O(log n + k) query, O(log n) insert)

Maintain a sorted list of timestamps for each tweet. When recording a tweet, insert the timestamp while keeping the list sorted (or append and sort lazily). During a query, use binary search to find the first timestamp within the requested range, then iterate through relevant timestamps to count them per bucket. Each bucket corresponds to a fixed interval (60 seconds for minute, 3600 for hour, 86400 for day). This reduces unnecessary scanning because timestamps before the range are skipped. Query complexity becomes O(log n + k) where k is the number of timestamps inside the range, and space complexity remains O(n).

Approach 3: TreeMap for Efficient Range Queries (O(log n + k) query, O(log n) insert)

Use a TreeMap (or any ordered set structure) to keep timestamps sorted automatically. Each tweet name maps to a TreeMap where keys are timestamps and values are occurrence counts. Recording a tweet inserts into the TreeMap in O(log n). For queries, use subMap(startTime, endTime) to retrieve only timestamps in the range, then distribute them into frequency buckets. This avoids scanning unrelated timestamps and keeps operations efficient even with large datasets.

Recommended for interviews: The sorted structure approach (Sorted List or TreeMap) is what interviewers typically expect. The brute force version demonstrates understanding of the problem, but the optimized design shows you know how to combine ordered data structures with range queries. TreeMap is especially clean in Java because subMap directly provides the required time slice.

Approach 1: Using Sorted List

This approach uses a sorted list to maintain tweet times for each tweet name. When querying, it computes the number of time chunks based on frequency and counts tweets within each chunk.

This solution uses a dictionary to store lists of tweet times, indexed by tweet name. For each call to getTweetCountsPerFrequency, it calculates the appropriate interval for the given frequency, and uses a loop to count the number of tweets in each time chunk. The counts are stored in a list, which is returned. The use of direct indexing ensures that we obtain count results efficiently.

Code

Python

Java

Complexity

Time Complexity: O(n), where n is the number of tweets of the specified tweet name. We iterate through each relevant time once.
Space Complexity: O(m), where m is the number of recorded times, as we store them in a dictionary.

Try this approach in the editor →

Approach 2: Using TreeMap for Efficient Range Querying

The second approach makes use of a TreeMap, which allows us to efficiently manage and query a sorted set of elements. This is particularly useful for efficiently accessing the times that fall within the specific chunks, taking advantage of logarithmic time complexity for lookups.

This Java solution employs a more sophisticated data structure, a TreeMap, which keeps entries sorted by their keys. For each tweet, the TreeMap records the count of tweets at exact times. The range query to obtain counts in a given chunk is efficiently handled by TreeMaps' subMap method, which provides a view of the portion of the map whose keys range from start (inclusive) to end (inclusive).

Code

Java

Complexity

Time Complexity: O((n + k) log m) per query, where n is the number of timestamps in the range query, k is the number of chunks, and m is the size of the timestamp map.
Space Complexity: O(m), where m is the number of unique timestamps stored in the TreeMap.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using Sorted List

Time Complexity: O(n), where n is the number of tweets of the specified tweet name. We iterate through each relevant time once.
Space Complexity: O(m), where m is the number of recorded times, as we store them in a dictionary.

Using TreeMap for Efficient Range Querying

Time Complexity: O((n + k) log m) per query, where n is the number of timestamps in the range query, k is the number of chunks, and m is the size of the timestamp map.
Space Complexity: O(m), where m is the number of unique timestamps stored in the TreeMap.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force with Unsorted ListInsert: O(1), Query: O(n)O(n)Simple implementation when number of tweets per user is small
Sorted List + Binary SearchInsert: O(log n), Query: O(log n + k)O(n)General solution when many range queries are expected
TreeMap / Ordered MapInsert: O(log n), Query: O(log n + k)O(n)Best choice in Java for clean range queries using subMap

Video Solution

Leetcode 1348. Tweet Counts Per Frequency • Fraz • 5,745 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Tweet Counts Per Frequency easy or hard?
Tweet Counts Per Frequency is a medium-level design problem. The logic is straightforward, but choosing the right data structure for efficient range queries and frequency bucketing makes it slightly more challenging than standard array problems.
Tweet Counts Per Frequency Python/Java solution
Python implementations usually maintain a sorted list of timestamps and use the bisect module for binary search. Java solutions often use TreeMap so timestamps remain ordered and subMap can quickly return the relevant range for counting.
How to solve Tweet Counts Per Frequency in O(log n + k)?
Store timestamps for each tweet in a sorted data structure. Use binary search (or TreeMap.subMap in Java) to quickly find the first timestamp within the range. Then iterate only through timestamps in that range and place them into frequency buckets based on the interval size.
What is the best approach for Tweet Counts Per Frequency?
The most practical solution stores timestamps in a sorted structure and performs range queries. A sorted list with binary search or a TreeMap allows efficient retrieval of timestamps between startTime and endTime. Query complexity becomes O(log n + k), where k is the number of tweets in the requested interval.
Is Tweet Counts Per Frequency asked at Google/Amazon/Meta?
Design-style problems involving time-based counters and range queries frequently appear at companies like Google, Amazon, and Meta. This problem tests understanding of ordered data structures, efficient querying, and system-style API design.
What data structure is used in Tweet Counts Per Frequency?
Common implementations use a hash table to map tweet names to timestamp collections, combined with a sorted data structure. Options include a sorted list with binary search or a TreeMap (ordered map) for efficient range queries.
What is the time complexity of Tweet Counts Per Frequency?
Recording a tweet takes O(log n) time when using a sorted structure like a TreeMap or a sorted list insertion. Retrieving tweet counts takes O(log n + k) time because the algorithm first locates the range using binary search or ordered map operations, then iterates over timestamps within that range.

Ready to solve this problem?

Practice Tweet Counts Per Frequency with our built-in code editor and test cases.

Practice on FleetCode