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
kdifferent tags, return all of them. kis 0 or more.tagshas 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
- First Badge Scanned Twice (Easy)
- Spell It With Tiles (Easy)
- Two Parcels, Exact Load (Easy)
- First One-of-a-Kind Character (Easy)
- Group Words With the Same Letters (Medium)
- Longest Streak of Floors (Medium)
- Everyone Else's Product (Medium)
- First Free Ticket Number (Hard)
- Most Lamp Posts in One Line (Hard)