Top Hashtags in a Time Window
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given parallel lists tweets and timestamps of equal length, each index i represents a post with text tweets[i] published at integer moment timestamps[i]. You also receive two integers, currentTime and timeWindow.
Filter the feed to keep only posts stamped inside the closed range [currentTime - timeWindow, currentTime] (both boundary timestamps count; posts earlier than currentTime - timeWindow or later than currentTime are ignored).
Split each retained post on whitespace into word tokens. Every token whose first character is '#' is treated as a hashtag (tokens where '#' appears only after the first character, such as "v2#rc1", do not qualify). Each appearance of a hashtag adds 1 to its total tally—including repeated appearances inside the same post.
Return a list containing up to 3 distinct hashtags ranked from highest total tally to lowest. Break frequency ties using standard ascending lexicographical (ASCII) string order. When fewer than 3 distinct hashtags occur in the active range, return all of them in ranked order (or [] when none occur).
Examples
Example 1
Input:
tweets = [
"shipped #rust and #linux patch",
"#rust benchmark results",
"archived #linux note",
"scheduled #cloud post"
]
timestamps = [200, 204, 180, 210]
currentTime = 205
timeWindow = 10
Output: ["#rust", "#linux"]
Explanation: The active interval is [195, 205]. Posts at 180 (too old) and 210 (after currentTime) are excluded. Across the remaining posts at 200 and 204, #rust occurs 2 times and #linux occurs 1 time. Fewer than 3 distinct hashtags exist, so both are returned.
Example 2
Input:
tweets = ["#ml #ops #ml", "#ops #db #web", "#db #db #ops"]
timestamps = [30, 32, 35]
currentTime = 35
timeWindow = 5
Output: ["#db", "#ops", "#ml"]
Explanation: Every post lies within [30, 35]. Counting every token occurrence yields #db: 3, #ops: 3, #ml: 2, and #web: 1. #db and #ops tie at 3, and "#db" < "#ops" alphabetically, followed by #ml at 2; #web places fourth and is omitted.
Example 3
Input:
tweets = ["release v2#rc1 is live", "plain status update", "early #alert"]
timestamps = [48, 50, 10]
currentTime = 50
timeWindow = 5
Output: []
Explanation: Within [45, 50], "v2#rc1" does not begin with '#' and "plain status update" contains no '#'. The post with #alert at 10 lies outside the window, leaving zero hashtags.
Constraints
len(tweets) == len(timestamps)0 <= len(tweets) <= 10^50 <= timeWindow- Timestamps and
currentTimeare integers; window endpointscurrentTime - timeWindowandcurrentTimeare both inclusive. - Tokens are delimited by arbitrary whitespace runs (
" ","\t","\n"), and hashtag matching is case-sensitive.
Step-by-step walkthrough
Understand the problem and filtering rules
We receive parallel lists
tweetsandtimestamps, wheretweets[i]was published attimestamps[i], along withcurrentTimeandtimeWindow. Our goal is to return up to3top hashtags from the active window.Let's pin down each rule before writing code:
- Inclusive time window: Keep a post if and only if
currentTime - timeWindow <= timestamp <= currentTime. Both endpoints count, and posts stamped aftercurrentTimeare excluded too. - Hashtag definition: Split each post on whitespace into tokens. A token is a hashtag if its first character is
#(so#rustcounts, whilev2#rc1does not). Tokens keep their exact characters and casing. - Count every occurrence: If a single post says
'#db #db #ops',#dbgains2and#opsgains1. - Ranking and tie-breaking: Order hashtags by count descending, breaking ties in lexicographical order (standard ASCII character order, such as
'#a' < '#ab' < '#b'). Return up to3hashtags, or all of them when fewer exist.
Example 1 timeline: currentTime = 205, timeWindow = 10 --> window [195, 205] t = 180 t = 195 t = 200 t = 204 t = 205 t = 210 "archived #linux..." [--------- "shipped #rust and #linux patch" "#rust benchmark results" ] "scheduled #cloud..." (too early -> skip) (inside -> counted) (inside -> counted) (too late -> skip)- Inclusive time window: Keep a post if and only if
Phase 1: Filter posts and count hashtag occurrences
We can walk
tweetsandtimestampsside by side withzip(tweets, timestamps)and accumulate tallies in a dictionarycounts.Two small Python choices prevent subtle bugs here:
- Use
tweet.split()with no arguments, nottweet.split(" "). Callingsplit()with no arguments treats any run of spaces, tabs (\t), or newlines (\n) as a single separator and never produces empty""tokens. - Use
token.startswith("#"), not"#" in token. A#buried inside a word likev2#rc1does not begin a hashtag token.
from typing import Dict, List def count_hashtags_in_window( tweets: List[str], timestamps: List[int], window_start: int, window_end: int, ) -> Dict[str, int]: """Count every hashtag occurrence in tweets whose timestamp lies in [window_start, window_end].""" # counts: maps each hashtag string to its occurrence count, e.g. {"#rust": 2, "#linux": 1} counts: Dict[str, int] = {} for tweet, timestamp in zip(tweets, timestamps): # Both window endpoints are inclusive; skip tweets before window_start or after window_end. if timestamp < window_start or timestamp > window_end: continue # split() splits on any whitespace run (spaces, tabs, newlines) with no empty strings. for token in tweet.split(): # Only tokens beginning with '#' count as hashtags ("v2#rc1" is ignored). if token.startswith("#"): counts[token] = counts.get(token, 0) + 1 return counts- Use
Phase 2: Sort by count descending, then tag ascending
Once we have
counts, we want higher counts first, but alphabetically smaller tags first when counts tie.Why can't we just sort
(count, tag)withreverse=True? Becausereverse=Trueflips both parts of the tuple:(3, "#ops")would come before(3, "#db"), breaking the tie-break rule!Instead, negate the count to build
(-count, tag)and sort in normal ascending order:Hashtag count tuple (-count, tag) why ascending sort works ------- ----- ------------------- -------------------------------------------------- "#db" 3 (-3, "#db") -3 < -2 puts count 3 ahead of count 2; "#ops" 3 (-3, "#ops") for tied -3, "#db" < "#ops" puts "#db" first "#ml" 2 (-2, "#ml") "#web" 1 (-1, "#web")After sorting, slicing
ranked[:3]extracts up to3winners without needing special cases when there are0,1, or2hashtags.from typing import Dict, List, Tuple def find_top_hashtags( tweets: List[str], timestamps: List[int], currentTime: int, timeWindow: int, ) -> List[str]: window_start = currentTime - timeWindow window_end = currentTime counts = count_hashtags_in_window(tweets, timestamps, window_start, window_end) # ranked: list of (-count, tag) tuples, e.g. [(-3, "#db"), (-3, "#ops"), (-2, "#ml")]. # Negating count lets a single ascending sort rank highest count first, # while ties automatically fall back to ascending lexicographical tag order. ranked: List[Tuple[int, str]] = [] for tag, count in counts.items(): ranked.append((-count, tag)) ranked.sort() # Slicing [:3] safely returns fewer than 3 hashtags (or []) when fewer exist. top_tags: List[str] = [] for negative_count, tag in ranked[:3]: top_tags.append(tag) return top_tagsWalk through Example 1 and Example 2
Example 1:
tweets = ['shipped #rust and #linux patch', '#rust benchmark results', 'archived #linux note', 'scheduled #cloud post'],timestamps = [200, 204, 180, 210],currentTime = 205,timeWindow = 10. - Active window is[195, 205]. - Posts at180(180 < 195) and210(210 > 205) are skipped. - Remaining posts yieldcounts = {'#rust': 2, '#linux': 1}. -rankedsorts to[(-2, '#rust'), (-1, '#linux')], returning['#rust', '#linux'].Example 2:
tweets = ['#ml #ops #ml', '#ops #db #web', '#db #db #ops'],timestamps = [30, 32, 35],currentTime = 35,timeWindow = 5.Window [30, 35] keeps all three posts: t = 30: "#ml #ops #ml" --> #ml: 2, #ops: 1 t = 32: "#ops #db #web" --> #ml: 2, #ops: 2, #db: 1, #web: 1 t = 35: "#db #db #ops" --> #ml: 2, #ops: 3, #db: 3, #web: 1 Sorted (-count, tag) tuples: 1. (-3, "#db") 2. (-3, "#ops") <-- tied at 3 with "#db", ordered alphabetically 3. (-2, "#ml") 4. (-1, "#web") <-- dropped by [:3] Result: ["#db", "#ops", "#ml"]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_hashtags_in_window( tweets: List[str], timestamps: List[int], window_start: int, window_end: int, ) -> Dict[str, int]: """Count every hashtag occurrence in tweets whose timestamp lies in [window_start, window_end].""" # counts: maps each hashtag string to its occurrence count, e.g. {"#rust": 2, "#linux": 1} counts: Dict[str, int] = {} for tweet, timestamp in zip(tweets, timestamps): # Both window endpoints are inclusive; skip tweets before window_start or after window_end. if timestamp < window_start or timestamp > window_end: continue # split() splits on any whitespace run (spaces, tabs, newlines) with no empty strings. for token in tweet.split(): # Only tokens beginning with '#' count as hashtags ("v2#rc1" is ignored). if token.startswith("#"): counts[token] = counts.get(token, 0) + 1 return counts def find_top_hashtags( tweets: List[str], timestamps: List[int], currentTime: int, timeWindow: int, ) -> List[str]: window_start = currentTime - timeWindow window_end = currentTime counts = count_hashtags_in_window(tweets, timestamps, window_start, window_end) # ranked: list of (-count, tag) tuples, e.g. [(-3, "#db"), (-3, "#ops"), (-2, "#ml")]. # Negating count lets a single ascending sort rank highest count first, # while ties automatically fall back to ascending lexicographical tag order. ranked: List[Tuple[int, str]] = [] for tag, count in counts.items(): ranked.append((-count, tag)) ranked.sort() # Slicing [:3] safely returns fewer than 3 hashtags (or []) when fewer exist. top_tags: List[str] = [] for negative_count, tag in ranked[:3]: top_tags.append(tag) return top_tags✅ Submit now — all tests should pass.
Intuition & how it works
Think of tallying paper ballots cast inside an official voting window: first, set aside any ballot stamped too early or too late; second, scan every hashtag written on each eligible ballot and add a tally mark to that hashtag's counter; third, rank candidates from highest tally to lowest, breaking ties in lexicographical order (standard character-code/dictionary order from left to right, such as '#db' before '#ops').
Shortcuts fail on subtle details here. Counting whether a post mentions a tag instead of counting every word token (a whitespace-separated piece of text) undercounts repeated tags like '#ml #ops #ml'. Likewise, sorting (count, tag) pairs with reverse=True puts the highest counts first, but accidentally flips alphabetical tie-breaking backwards ('#ops' before '#db'). Negating the count to form (-count, tag) lets one standard ascending sort put larger counts first (-3 < -2) while keeping tied tags in ascending order ('#db' < '#ops').
Walk through tweets = ['#ml #ops #ml', '#ops #db', 'early #ml'], timestamps = [30, 34, 15], currentTime = 35, timeWindow = 5:
- Active window is [35 - 5, 35] = [30, 35], so timestamp 15 ('early #ml') is skipped.
- Post at 30 ('#ml #ops #ml') gives counts = {'#ml': 2, '#ops': 1}; post at 34 ('#ops #db') updates it to {'#ml': 2, '#ops': 2, '#db': 1}.
- Tuples (-2, '#ml'), (-2, '#ops'), (-1, '#db') sort in that exact order, returning ['#ml', '#ops', '#db'].
Complexity
Let n be the number of posts, C be the total number of characters across posts inside the time window, and h be the number of distinct hashtags found (h <= C).
- Time:
O(n + C + h log h)(orO(n + C log h)character comparisons if hashtags are very long). We inspect allntimestamps once inO(n), split and hash the characters of in-window posts inO(C), and sorth(-count, tag)pairs inO(h log h)tuple comparisons. - Space:
O(C)worst-case (O(h)dictionary entries andrankedtuples storing the distinct hashtag strings, plus the temporary token list of a single post at a time).
Edge cases
- Exact window boundaries: Posts at
currentTime - timeWindowand atcurrentTimeare both included. - Future timestamps (
timestamp > currentTime): Excluded by the upper bound checktimestamp > window_end. - Zero-width window (
timeWindow = 0): Only posts withtimestamp == currentTimeare counted. - Empty input or zero hashtags in window:
countsis empty,ranked[:3]is[], and the function returns[]. - Fewer than 3 distinct hashtags: Slicing
[:3]returns all available hashtags in sorted order without raising an index error. - Repeated tag inside one post (
'#x #x #x'): Counted3times, beating a tag that appears once in each of two posts. #inside a word ('v2#rc1'): Ignored becausestartswith('#')checks only index0of the token.- Multiple spaces, tabs, or newlines:
tweet.split()collapses arbitrary whitespace runs cleanly.
Common mistakes
- Counting unique posts per hashtag instead of total occurrences: Wrapping
tweet.split()inset(...)undercounts repeated mentions inside a single post (['#x #x #x', '#y', '#y']ranks#xfirst at3vs2, whereas per-post counting ranks#yfirst at2vs1). - Sorting
(count, tag)withreverse=True: Reverses tie-breaking so'#ops'beats'#db'when counts are equal. - Using
<instead of<=on window endpoints, or forgettingtimestamp <= currentTime: Drops boundary posts or accidentally counts future posts. - Calling
tweet.split(' '): Fails to split on\tor\nand produces empty''strings when spaces repeat. - Checking
'#' in token: Misclassifies'v2#rc1'or URL fragments as hashtags.
Alternative approaches
- Bounded selection with a heap (
heapq.nsmallest(3, ranked)): A min-heap is a binary tree structure that tracks the smallest item inO(1)time and updates inO(log k)time. Callingheapq.nsmallest(3, ((-count, tag) for tag, count in counts.items()))finds the top3inO(h log 3) = O(h)comparisons instead ofO(h log h), which helps ifhis huge andk = 3stays tiny. collections.Counter: Handy for accumulating counts, thoughCounter.most_common(3)breaks ties by first-seen insertion order rather than alphabetical order, so you still need a custom(-count, tag)key.
Follow-up questions
- How would you maintain the top 3 hashtags if posts arrive in a continuous stream and queries advance currentTime monotonically? Store
(timestamp, tag)occurrences in acollections.dequein chronological order alongside a livecountsdictionary. Whenever a query arrives atnow, pop expired entries withtimestamp < now - timeWindowfrom the left of the deque and decrement their counts (deleting keys that hit0), then takeheapq.nsmallest(3, ...)overcounts. Because each hashtag occurrence enters and leaves the deque at most once, window maintenance takes amortizedO(1)time (constant average cost per operation over the whole stream) per occurrence, and each query takesO(h)over active distinct tags.
```python import heapq from collections import deque
class StreamingTopHashtags: def init(self, time_window: int): self.time_window = time_window self.events = deque() # (timestamp, tag) in non-decreasing timestamp order self.counts = {}
def add_tweet(self, tweet: str, timestamp: int) -> None:
for token in tweet.split():
if token.startswith("#"):
self.events.append((timestamp, token))
self.counts[token] = self.counts.get(token, 0) + 1
def top3(self, current_time: int):
cutoff = current_time - self.time_window
while self.events and self.events[0][0] < cutoff:
_, old_tag = self.events.popleft()
self.counts[old_tag] -= 1
if self.counts[old_tag] == 0:
del self.counts[old_tag]
candidates = [(-count, tag) for tag, count in self.counts.items()]
return [tag for _, tag in heapq.nsmallest(3, candidates)]
```
-
How would you normalize hashtags so casing differences and trailing punctuation such as #Rust, #rust, and #rust! map to the same tag? Still split on whitespace first so mid-word
#characters likev2#rc1are rejected, then match#\w+at the start of each token (re.match(r"#\w+", token)) and lowercase the matched prefix. That strips trailing punctuation like!or,, merges uppercase/lowercase variants, and ignores bare#tokens with no word characters after them. -
How would you compute the top 3 hashtags across billions of posts partitioned across many machines? Avoid taking only each server's local top
3and merging them: a hashtag ranked 4th on every server could easily have the highest global total! For an exact answer, route each hashtag occurrence to a counting shard usinghash(tag) % num_shardsso every occurrence of#rustlands on the same shard; then each shard emits its local top3and a coordinator merges those3 * num_shardscandidates accurately. If approximate counts are acceptable under tight memory, a Count-Min Sketch (a compact multi-hash frequency table that estimates item counts in fixed memory) paired with a small heavy-hitters heap tracks top tags in sublinear space.
Follow-up questions
- How would you maintain the top 3 hashtags if posts arrive in a continuous stream and queries advance currentTime monotonically?
- How would you normalize hashtags so casing differences and trailing punctuation such as #Rust, #rust, and #rust! map to the same tag?
- How would you compute the top 3 hashtags across billions of posts partitioned across many machines?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array