Trending Tags in Time Window
StringsAuto-graded · 20 test casesLast updated
Tests filtering by time range, frequency counting with a dictionary, and sorting with multi-level tie-breaking rules.
You receive two parallel arrays of length n:
tweets[i]: the text content of tweeti(a string)timestamps[i]: when tweetiwas published (an integer)
You also receive:
current_time: the reference timestamptime_window: the lookback duration
Your task is to identify the most popular tags from tweets published in the time range [current_time - time_window, current_time] (inclusive on both ends).
Tag definition: A tag is any whitespace-delimited token that begins with the # character. Tags are case-sensitive and include all characters after # until whitespace. The same tag appearing multiple times in a single tweet is counted multiple times.
Popularity: The popularity of a tag equals the total number of times it appears across all tweets within the time window.
Return up to 3 tags, ordered by:
- Popularity (descending: more popular first)
- Lexicographic order (ascending) to break ties
If fewer than 3 distinct tags exist in the window, return all of them in the specified order.
Constraints
1 ≤ n ≤ 10⁵0 ≤ len(tweets[i]) ≤ 5000 ≤ timestamps[i], current_time ≤ 10⁹0 ≤ time_window ≤ 10⁹- Tweets are tokenized by splitting on whitespace (any runs of spaces, tabs, newlines)
- A token qualifies as a tag if and only if its first character is
# - Tags
#AIand#aiare distinct;#tagand#tag!are distinct
Examples
Example 1
Input: trending_tags(['I love #python and #coding', '#python is great', 'old #coding'], [100, 105, 50], 105, 10)
Output: ['#python', '#coding']
Example 2
Input: trending_tags(['#a #b #a', '#b #c', '#c #c #b'], [10, 11, 12], 12, 2)
Output: ['#b', '#c', '#a']
Example 3
Input: trending_tags(['nothing here', 'still no tags'], [5, 6], 10, 2)
Output: []
Hints
Hint 1
Filter the tweets first: only process those whose timestamp falls within the inclusive range [current_time - time_window, current_time].
Hint 2
Use a dictionary or Counter to track how many times each tag appears across the filtered tweets. Remember that .split() with no arguments handles all whitespace.
Hint 3
Sort the tags using a composite key: (-count, tag_string). This handles both ordering requirements in one pass, then take the first 3 results.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem follows a filter-count-rank pattern:
-
Filter by time window: Only consider tweets where
current_time - time_window ≤ timestamp ≤ current_time. Both boundaries are inclusive. -
Extract and count tags: For each qualifying tweet, split it on whitespace using
.split(). Every token starting with#is a tag. Accumulate counts in a frequency map (usingCounteror a dictionary). -
Rank and select top 3: Sort all tags by a composite key
(-count, tag). The negative count ensures higher popularity comes first. The tag string as secondary key breaks ties in ascending lexicographic order. Take the first 3 entries from the sorted result.
Why It Works
The inclusive time filter captures exactly the tweets in range. Each tag occurrence increments its counter once, so the final count equals total appearances. The composite sort key (-count, tag) produces a total ordering where popularity dominates and alphabetical order resolves ties, matching the requirements exactly. Slicing [:3] naturally handles cases with fewer than 3 tags.
Complexity
- Time: O(n + L + k log k), where L is the total character count across all tweets and k is the number of distinct tags. Filtering and counting scan all relevant text once. Sorting k tags dominates.
- Space: O(k) for the frequency map, plus temporary space for tokenization.
Note: Since only 3 results are needed, using heapq.nsmallest(3, ...) reduces the ranking step to O(k), though full sorting is acceptable for this problem size.
Solution
from collections import Counter
from typing import List
def trending_tags(tweets: List[str], timestamps: List[int], current_time: int, time_window: int) -> List[str]:
counts = Counter()
start = current_time - time_window
for tweet, timestamp in zip(tweets, timestamps):
if start <= timestamp <= current_time:
for token in tweet.split():
if token.startswith('#'):
counts[token] += 1
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return [tag for tag, _ in ranked[:3]]