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^5
  • 0 <= timeWindow
  • Timestamps and currentTime are integers; window endpoints currentTime - timeWindow and currentTime are both inclusive.
  • Tokens are delimited by arbitrary whitespace runs (" ", "\t", "\n"), and hashtag matching is case-sensitive.

Step-by-step walkthrough

  1. Understand the problem and filtering rules

    We receive parallel lists tweets and timestamps, where tweets[i] was published at timestamps[i], along with currentTime and timeWindow. Our goal is to return up to 3 top hashtags from the active window.

    Let's pin down each rule before writing code:

    1. Inclusive time window: Keep a post if and only if currentTime - timeWindow <= timestamp <= currentTime. Both endpoints count, and posts stamped after currentTime are excluded too.
    2. Hashtag definition: Split each post on whitespace into tokens. A token is a hashtag if its first character is # (so #rust counts, while v2#rc1 does not). Tokens keep their exact characters and casing.
    3. Count every occurrence: If a single post says '#db #db #ops', #db gains 2 and #ops gains 1.
    4. 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 to 3 hashtags, 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)
    
  2. Phase 1: Filter posts and count hashtag occurrences

    We can walk tweets and timestamps side by side with zip(tweets, timestamps) and accumulate tallies in a dictionary counts.

    Two small Python choices prevent subtle bugs here:

    • Use tweet.split() with no arguments, not tweet.split(" "). Calling split() 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 like v2#rc1 does 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
    
  3. 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) with reverse=True? Because reverse=True flips 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 to 3 winners without needing special cases when there are 0, 1, or 2 hashtags.

    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_tags
    
  4. Walk 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 at 180 (180 < 195) and 210 (210 > 205) are skipped. - Remaining posts yield counts = {'#rust': 2, '#linux': 1}. - ranked sorts 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"]
    
  5. 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) (or O(n + C log h) character comparisons if hashtags are very long). We inspect all n timestamps once in O(n), split and hash the characters of in-window posts in O(C), and sort h (-count, tag) pairs in O(h log h) tuple comparisons.
  • Space: O(C) worst-case (O(h) dictionary entries and ranked tuples 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 - timeWindow and at currentTime are both included.
  • Future timestamps (timestamp > currentTime): Excluded by the upper bound check timestamp > window_end.
  • Zero-width window (timeWindow = 0): Only posts with timestamp == currentTime are counted.
  • Empty input or zero hashtags in window: counts is 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'): Counted 3 times, beating a tag that appears once in each of two posts.
  • # inside a word ('v2#rc1'): Ignored because startswith('#') checks only index 0 of 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() in set(...) undercounts repeated mentions inside a single post (['#x #x #x', '#y', '#y'] ranks #x first at 3 vs 2, whereas per-post counting ranks #y first at 2 vs 1).
  • Sorting (count, tag) with reverse=True: Reverses tie-breaking so '#ops' beats '#db' when counts are equal.
  • Using < instead of <= on window endpoints, or forgetting timestamp <= currentTime: Drops boundary posts or accidentally counts future posts.
  • Calling tweet.split(' '): Fails to split on \t or \n and 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 in O(1) time and updates in O(log k) time. Calling heapq.nsmallest(3, ((-count, tag) for tag, count in counts.items())) finds the top 3 in O(h log 3) = O(h) comparisons instead of O(h log h), which helps if h is huge and k = 3 stays tiny.
  • collections.Counter: Handy for accumulating counts, though Counter.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 a collections.deque in chronological order alongside a live counts dictionary. Whenever a query arrives at now, pop expired entries with timestamp < now - timeWindow from the left of the deque and decrement their counts (deleting keys that hit 0), then take heapq.nsmallest(3, ...) over counts. Because each hashtag occurrence enters and leaves the deque at most once, window maintenance takes amortized O(1) time (constant average cost per operation over the whole stream) per occurrence, and each query takes O(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 like v2#rc1 are 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 3 and 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 using hash(tag) % num_shards so every occurrence of #rust lands on the same shard; then each shard emits its local top 3 and a coordinator merges those 3 * num_shards candidates 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

Similar questions

More F5Networks interview questions

All 1 F5Networks questions →