Payments app~45 min2s · 256 MBtarget O(n log² n) time, O(n) spacedivide-and-conquer
A payments app logs a stream of events in time order. A transaction event records the amount and the fee of a payment. An audit event asks a question about the payments that came before it.
The question is: "How many earlier transactions had an amount at most a and a fee at most b?" All the events are known in advance, and a log can have 40,000 events.
Write count_dominated(events).
events[i] = [kind, x, y] is the i-th event. When kind is 0, it is a transaction with amount x and fee y, in units. When kind is 1, it is an audit question with the limits x for the amount and y for the fee.x and a fee at most y. Equal values count.Input: events = [[0, 3, 5], [0, 1, 2], [1, 4, 5], [0, 2, 9], [1, 3, 5], [0, 4, 1], [1, 5, 9]]
Output: [2, 2, 4]The events are numbered 0 to 6 in time order. The recursion splits the time range in half, solves each half, and then counts the transactions of the left half for the questions of the right half:
| Time range | Split after | Questions of the right half that gain | Gain |
|---|---|---|---|
| events 1 to 2 | 1 | event 2 | 1 |
| events 0 to 2 | 0 | event 2 | 1 |
| events 5 to 6 | 5 | event 6 | 1 |
| events 3 to 6 | 4 | event 6 | 1 |
| events 0 to 6 | 2 | events 4 and 6 | 2 each |
The question at event 2 gets 1 + 1 = 2. The question at event 4 gets 2. The question at event 6 gets 1 + 1 + 2 = 4. The answers are 2, 2, 4.
Input: events = [[0, 5, 5], [1, 4, 9], [1, 5, 5]]
Output: [0, 1]The transaction has amount 5, which is above the first question's amount limit of 4. It fits the second question exactly, and equal values count.
Input: events = [[0, 1, 1], [0, 2, 2]]
Output: []There is no audit question.
1 ≤ len(events) ≤ 40,000kind is 0 or 1, and 0 ≤ x, y ≤ 1,000,000Looking back at every earlier event for each question takes up to about 240 million steps for 40,000 events. That is too slow for a 2-second limit. The three conditions, time, amount and fee, cannot all be handled by a plain sort or a plain tree, because each handles only two.