Problem 425306 · medium · Level 04 Non-Linear Data Structures

Trending Hashtags

heaps · counting · tie-breaking · top-k

Given a list of hashtag strings tags and an integer k, return the k most frequent hashtags. Order the result by frequency from highest to lowest; when two hashtags have the same frequency, the one that is alphabetically smaller comes first.

Examples

Input:  tags = ["rain", "jazz", "rain", "chess", "jazz", "rain", "kites", "chess", "kites", "jazz"], k = 3
Output: ["jazz", "rain", "chess"]
Explanation: counts are jazz=3, rain=3, chess=2, kites=2. "jazz" comes before "rain"
             alphabetically, and "chess" beats "kites" for the last place.

Input:  tags = ["b", "a", "b", "a"], k = 2
Output: ["a", "b"]
Explanation: both appear twice; "a" wins the alphabetical tie-break.

Constraints

  • 1 <= len(tags) <= 10**5, each tag is a non-empty lowercase string
  • 1 <= k <= number of distinct tags
  • Target complexity: O(n + m log k) where m is the number of distinct tags.

Goals

  • Count occurrences with a dictionary
  • Build a composite key so frequency and alphabetical order are compared in the right direction
  • Select the top k entries in O(m log k)
Starting Python…