Social feed~35 min2s · 256 MBtarget O(n log n) time, O(n) spacefenwick-tree
A feed app scores each post it shows, and it records the scores in the order the posts were shown. The ranking team wants to know how a post compares with the posts the reader saw before it.
For each post, they count how many of the previous w posts had a strictly higher score. Your team lead asks: "Give me that count for every post in the list."
Write outranked_counts(scores, w).
scores is the list of post scores, in the order shown.w is the window: for post i, look at the posts i - w to i - 1, or fewer when there are fewer posts before it.Input: scores = [5, 3, 8, 6, 2, 7], w = 3
Output: [0, 1, 0, 1, 3, 1]For each post, the window holds at most the 3 posts before it. The table counts the higher scores in each window.
| Post | Score | Window before it | Higher scores in the window |
|---|---|---|---|
| 0 | 5 | [] | 0 |
| 1 | 3 | [5] | 1 |
| 2 | 8 | [5, 3] | 0 |
| 3 | 6 | [5, 3, 8] | 1 |
| 4 | 2 | [3, 8, 6] | 3 |
| 5 | 7 | [8, 6, 2] | 1 |
Input: scores = [1, 2, 3], w = 2
Output: [0, 0, 0]The scores rise, so no earlier post has a higher score than the one after it.
Input: scores = [4, 4, 4], w = 5
Output: [0, 0, 0]The scores are equal, and an equal score is not higher, so every count is 0 even though the window is longer than the list.
1 ≤ len(scores) ≤ 30,0000 ≤ scores[i] ≤ 1,000,000,0001 ≤ w ≤ 30,000Looking back over the window costs up to 15,000 steps for each of 30,000 posts. That is about 337,492,500 steps in all. A Fenwick tree over the ranks of the scores keeps the posts of the window. It answers how many of them rank at most a given rank, and each post costs about 45 steps.