Chat app~25 min2s · 256 MBtarget O(n log n) time, O(n) spacefenwick-tree
You work on a chat app with a priority inbox. Every message that arrives gets a score, a whole number up to a billion, and a low score means high urgency.
A moderation screen keeps asking: "How many messages so far have a score of at most v?" The log mixes arrivals and questions in time order, and it can hold 100,000 events.
Write count_so_far(events).
events is a list in time order. Each event is [kind, v].[0, v] means a message with score v has arrived. Scores can repeat.[1, v] is a question: how many messages that arrived before this event have a score of at most v?Input: events = [[0, 40], [0, 10], [1, 25], [0, 25], [1, 25], [0, 40], [1, 40]]
Output: [1, 2, 4]Read the events in order. A question counts only the messages that have already arrived, so the same value of v can give a different answer later.
| Event | Scores so far, sorted | Answer |
|---|---|---|
| A message with score 40 arrives | [40] | none |
| A message with score 10 arrives | [10, 40] | none |
| How many have a score of at most 25? | [10, 40] | 1 |
| A message with score 25 arrives | [10, 25, 40] | none |
| How many have a score of at most 25? | [10, 25, 40] | 2 |
| A message with score 40 arrives | [10, 25, 40, 40] | none |
| How many have a score of at most 40? | [10, 25, 40, 40] | 4 |
The answers are the figures in the last column: 1, 2, 4.
Input: events = [[1, 5], [0, 5], [1, 4], [1, 5]]
Output: [0, 0, 1]A question before any arrival gives 0. A question for a score below the only message also gives 0.
Input: events = [[0, 7], [0, 7], [0, 7], [1, 7]]
Output: [3]Three messages with the same score all count when the question asks for at most that score.
1 ≤ len(events) ≤ 100,000kind is 0 or 1 and 0 ≤ v ≤ 1,000,000,000.Counting the earlier scores one by one reads up to 50,000 of them for every question, which can reach billions of reads. A table with one cell for every possible score is also out of reach, because scores go up to a billion. You need a way to shrink the scores to at most 100,000 positions and count over those positions quickly.