Social feed~45 min2s · 256 MBtarget O((n + q·k) log n) time, O(n) spaceheaps
A feed app shows a trending list. Each post carries one topic, and the list shows the topics with the most posts in the last stretch of time. Posts older than that stretch no longer count.
The app refreshes the list many times a day. Each refresh must be fast, even though the counts of topics rise as posts arrive and fall as posts get old.
Write trending(times, topics, window, queries, k).
i has topic topics[i] and arrives at second times[i]. The times never go down.q, a post counts when q - window < times[i] <= q. Posts after q do not exist yet.k topics with the most counted posts. Break ties by the smaller topic id. If fewer than k topics have a counted post, return all of them.Input: times = [1, 2, 3, 5, 6, 8, 9], topics = [5, 7, 5, 9, 7, 5, 9], window = 5, queries = [3, 6, 9, 12], k = 2
Output: [[5, 7], [7, 5], [9, 5], [5, 9]]The trace lists the counts of the posts that are inside each window.
| Query time | Event times in the window | Counts (topic: count) | Top 2 topics |
|---|---|---|---|
| 3 | 1 to 3 | 5: 2, 7: 1 | 5, 7 |
| 6 | 2 to 6 | 5: 1, 7: 2, 9: 1 | 7, 5 |
| 9 | 5 to 9 | 5: 1, 7: 1, 9: 2 | 9, 5 |
| 12 | 8 to 9 | 5: 1, 9: 1 | 5, 9 |
At time 6, topic 7 has two posts at times 2 and 6, so it leads. Topics 5 and 9 have one counted post each, and topic 5 wins the tie with the smaller id. At time 12, only the posts at times 8 and 9 are left.
Input: times = [10, 10, 20], topics = [1, 2, 2], window = 10, queries = [10, 19, 20, 100], k = 3
Output: [[1, 2], [1, 2], [2], []]At time 10, topics 1 and 2 have one post each. At time 19, both posts at time 10 are still counted. At time 20, they are exactly 10 seconds old, so only the post at 20 counts. At time 100, no post counts.
Input: times = [1, 2, 3, 4], topics = [8, 8, 8, 9], window = 100, queries = [4], k = 1
Output: [[8]]Topic 8 has three posts and topic 9 has one. With k = 1, only topic 8 is returned.
1 ≤ times.length ≤ 100,000; topics has the same length, with 1 ≤ topics[i] ≤ 1,000,000,0000 ≤ times[i] ≤ 2,678,400 (seconds since the start of the month), never going down1 ≤ window ≤ 86,400 (seconds)1 ≤ queries.length ≤ 100,000; queries are between 0 and 2,678,400 and never go down1 ≤ k ≤ 10Counting the posts in the window for every query costs about n × q = 10^10 steps. Moving the two ends of the window only forward costs 2 × n steps in total. But a heap cannot remove an entry from its middle when a count changes. Instead, push a new entry at every change, and discard entries that are out of date when they reach the top.