Problem 425306 · medium · Phase 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 = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: counts are the=4, is=3, sunny=2, day=1.

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…