Social feed~25 min2s · 256 MBtarget O(n + u log k) time, O(u) spaceclassic twin: lc-692heaps
A social app shows a "trending words" strip. Every post of the last hour is split into lowercase words, and all the words go into one list. The strip shows the k words used most often, the most used first.
A busy hour can hold 100,000 words, and many of them are different. Counting is easy. The work is choosing the best k. When two words are used equally often, the strip shows the one that comes first in alphabetical order, so the strip does not flicker.
Write top_words(words, k).
words[i] is a word of lowercase letters a to z. The same word can appear many times, and every copy counts as one use.k words with the most uses. A word with more uses comes before a word with fewer uses.pi comes before pie.k is larger than the number of different words, return every different word, in the same order.Input: words = ["rain", "sun", "rain", "fog", "sun", "rain", "fog", "wind"], k = 2
Output: ["rain", "fog"]The uses are rain 3, sun 2, fog 2 and wind 1. Keep a heap of at most k words with the weakest on top. A word is weaker with fewer uses, or with equal uses and a later place in alphabetical order. The words are taken in order of first appearance.
| Word | Uses | Weakest popped | Heap after the step (weakest first) |
|---|---|---|---|
| rain | 3 | none | rain |
| sun | 2 | none | sun, rain |
| fog | 2 | sun (a tie with fog, and sun is later) |
fog, rain |
| wind | 1 | wind (fewest uses) | fog, rain |
The heap pops the weakest first, so the words come out as fog, rain. Reversed, they are rain, fog.
Input: words = ["a", "b", "a"], k = 5
Output: ["a", "b"]There are only two different words, so both are returned, a with 2 uses first.
Input: words = ["pie", "pi", "pie", "pi"], k = 1
Output: ["pi"]Both words have 2 uses. pi is a prefix of pie, so it comes first alphabetically.
1 ≤ length of words ≤ 10^51 ≤ length of each word ≤ 12, lowercase letters a to z1 ≤ k ≤ 10^5The list has 100,000 words, and up to 100,000 of them can be different. Scanning every different word once for each of k answers can cost about 5 × 10^9 steps, which is too slow.
A hash map counts the words in one pass. After that, sorting all the different words costs about 1.7 × 10^6 comparisons and is fast enough. A heap of size k does the same job with memory for only k entries, and it is faster when k is small.