KatInterview

Trending Tags in Time Window

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringshash-mapsortingstring-parsing

Last 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 tweet i (a string)
  • timestamps[i]: when tweet i was published (an integer)

You also receive:

  • current_time: the reference timestamp
  • time_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:

  1. Popularity (descending: more popular first)
  2. 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]) ≤ 500
  • 0 ≤ 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 #AI and #ai are distinct; #tag and #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.