Social feed~25 min2s · 256 MBtarget O(n) time, O(n) spacewindow-counts · sliding-window-fixed · hashing
A social feed shows posts in a fixed order, and every post carries one topic id. The ranking team wants a "heat" score for any stretch of the feed that a person might see on one screen.
The heat of a window of k consecutive posts is the largest number of posts in it that share one topic. A window of 5 posts with three posts on topic 7 and two on topic 2 has a heat of 3.
The team scores every window of k posts and wants the total heat over all the windows. They use it to compare feeds that have the same length.
Write total_heat(topics, k).
topics[i] is the topic id of post i, in feed order.k consecutive posts. There are n - k + 1 of them, and they overlap.k is at least 1 and at most n.Input: topics = [3, 5, 3, 3, 8, 5, 5, 3], k = 4
Output: 11The loop adds the post at right, and a full window records its heat. Then the post at right - k + 1 leaves. The table shows the counts after the join and the heat of the window that was recorded last.
| right | Joins | Counts after the join | Heat of the window | Total so far | Leaves afterwards |
|---|---|---|---|---|---|
| 0 | 3 | 3→1 | |||
| 1 | 5 | 3→1, 5→1 | |||
| 2 | 3 | 3→2, 5→1 | |||
| 3 | 3 | 3→3, 5→1 | 3 | 3 | 3 (count 3 to 2) |
| 4 | 8 | 3→2, 5→1, 8→1 | 2 | 5 | 5 (count 1 to 0) |
| 5 | 5 | 3→2, 5→1, 8→1 | 2 | 7 | 3 (count 2 to 1) |
| 6 | 5 | 3→1, 5→2, 8→1 | 2 | 9 | 3 (count 1 to 0) |
| 7 | 3 | 3→1, 5→2, 8→1 | 2 | 11 | 8 (count 1 to 0) |
The five windows have heat 3, 2, 2, 2 and 2, and they add up to 11.
Input: topics = [4, 4, 4], k = 3
Output: 3There is one window, and all three posts share topic 4.
Input: topics = [1, 2, 3, 4], k = 2
Output: 3Every window holds two different topics, so each of the three windows has a heat of 1.
1 ≤ topics.length ≤ 100,000 (posts in the feed)1 ≤ topics[i] ≤ 10^6 (topic id)1 ≤ k ≤ topics.lengthCounting the topics of every window from scratch costs about n × k steps. With n = 100,000 and k = 50,000 that is 2.5 × 10^9, far over the limit. Rescanning the counts of a sliding window for the largest one costs as much as the number of different topics, which can also be large.
The total can reach 50,001 × 50,000 = 2.5 × 10^9. That is beyond a 32-bit integer, so use a 64-bit type (long in Java, long long in C++).