Polski

Most frequent tags

Count occurrences and pick the k most popular tags, breaking ties alphabetically. A counter map plus a heap of size k, or sorting.

medium · typescript · javascript · python · csharp · java · go · 20 XP

A blog shows a cloud of the k most popular tags. We have the list of all tag uses (with repetitions) and need to pick the most frequent ones.

Task

topKFrequent(words, k) returns a list of at most k distinct words:

  • sorted by number of occurrences, descending,
  • for equal counts – alphabetically ascending (character by character, like < on ASCII strings; "go" comes before "golang"),
  • when there are fewer than k distinct words, return all of them; for k = 0 – an empty list.

Signatures: topKFrequent(words, k) (JS/TS), top_k_frequent(words, k) (Python), Solution.TopKFrequent (C#), Solution.topKFrequent (Java), TopKFrequent (Go).

Examples

wordskResult
["api","db","api","cache","db","api"]2["api","db"]
["b","a","c","b","a","c"]2["a","b"] – a tie, the alphabet decides
["zeta","zeta","alpha"]5["zeta","alpha"]
[]3[]

Constraints

  • 0 ≤ words.length ≤ 300,000, 0 ≤ k ≤ 10,000, words made of lowercase ASCII letters, digits and -.

Expected complexity

O(n + m log k) time with a heap of size k (m – number of distinct words) or O(n + m log m) with sorting; O(m) memory.