Social feed~25 min2s · 256 MBtarget O(n + u log k) time, O(u) spacetop-k
You work on a social app that shows a "trending words" strip. Every post is a line of lowercase words separated by single spaces. The strip shows the k words used most often.
One person can repeat a word many times in one post to push it up, which is spam. So a word counts only when it appears in at least min_posts different posts. Your team lead asks: "Which words trend?" A day can hold 20,000 posts and many different words.
Write trending(posts, k, min_posts).
posts[i] is a post: words made of the letters a to z, with one space between two words, and no space at the start or the end.min_posts.k eligible words with the most uses, the most used first. On equal uses, the word that comes first in alphabetical order goes first. If fewer than k words are eligible, return all of them.Input: posts = ["now now now now now now buy", "shoes buy sale", "shoes shoes sale", "buy shoes", "sale buy shoes"], k = 2, min_posts = 2
Output: ["shoes", "buy"]| Word | Uses | Spread (different posts) | Eligible |
|---|---|---|---|
| now | 6 | 1 | no: it is spam |
| shoes | 5 | 4 | yes |
| buy | 4 | 4 | yes |
| sale | 3 | 3 | yes |
The best two eligible words are shoes (5 uses) and buy (4 uses). Without the spread rule, the strip would show now and shoes.
Input: posts = ["a a a"], k = 1, min_posts = 1
Output: ["a"]Input: posts = ["x y", "x z"], k = 2, min_posts = 3
Output: []No word appears in 3 different posts, so none is eligible.
1 ≤ posts.length ≤ 20,0001 ≤ posts[i].length ≤ 100, and a post holds the letters a to z and single spaces between words1 ≤ k ≤ 1001 ≤ min_posts ≤ 20,000A post of 100 characters holds up to 50 words. So the posts can hold about 100,000 to 200,000 words, and up to 100,000 of them can be different. Reading all posts again for each different word costs 20,000,000,000 steps.
One pass can count the uses and the spread of every word in a dictionary. Then a heap of size k picks the best words from the dictionary entries.