Trending Hashtags

Medium · Arrays & Hashing · about 20 min

A social app logs every hashtag used today in tags. Return the k most used tags, most used first.

  • If two tags are used the same number of times, the one that comes first alphabetically goes first (plain string order; every tag is lowercase letters).
  • If there are fewer than k different tags, return all of them.
  • k is 0 or more. tags has 0 to 100,000 entries.

Example:

trending_tags(["ai", "go", "ai", "rust", "go", "ai", "css"], 2) → ["ai", "go"] (ai is used 3 times, go 2 times)

Hints

  • Start by counting how many times each tag appears.
  • Then sort the distinct tags by two things: count (high to low), then the tag itself (A to Z).
  • In JavaScript, give sort a comparator that handles both parts; in Python a key like (minus count, tag) works.

Learn the pattern first: the Arrays & Hashing lesson.

More Arrays & Hashing problems