Music streaming app~25 min2s · 256 MBtarget O((n + q) log n) time, O(n) spaceprefix-sums · binary-search
A video streaming app logs one event each time a profile finishes watching: the profile, the day and the minutes watched. Most profiles watch on only some days, so the log is sparse and arrives in no particular order.
Parental controls and wellbeing reports ask the same kind of question many times: how many minutes did this profile watch between day A and day B?
Write watch_totals(profiles, days, minutes, qprofiles, qfrom, qto).
i says that profile profiles[i] watched for minutes[i] minutes on day days[i]. A profile may have several events on one day.q asks for the total minutes of profile qprofiles[q] on the days from qfrom[q] to qto[q], both days included.Input: profiles = [2, 1, 2, 1, 2, 3], days = [5, 3, 5, 4, 6, 1], minutes = [40, 25, 30, 60, 20, 15], qprofiles = [2, 2, 1, 1, 3], qfrom = [5, 5, 3, 5, 0], qto = [5, 6, 4, 9, 1]
Output: [70, 90, 85, 0, 15]The trace builds a key profile × 1000 + day for each event and sorts the events by it. The sorted keys are 1003, 1004, 2005, 2005, 2006, 3001, and the prefix sums of their minutes are 0, 25, 85, 125, 155, 175, 190.
| Query | Key range | First event at or after the start | First event after the end | Total |
|---|---|---|---|---|
| profile 2, days 5 to 5 | 2005 to 2005 | position 2 | position 4 | 155 - 85 = 70 |
| profile 2, days 5 to 6 | 2005 to 2006 | position 2 | position 5 | 175 - 85 = 90 |
| profile 1, days 3 to 4 | 1003 to 1004 | position 0 | position 2 | 85 - 0 = 85 |
| profile 1, days 5 to 9 | 1005 to 1009 | position 2 | position 2 | 85 - 85 = 0 |
| profile 3, days 0 to 1 | 3000 to 3001 | position 5 | position 6 | 190 - 175 = 15 |
The output is [70, 90, 85, 0, 15].
Input: profiles = [7, 7, 7], days = [2, 2, 2], minutes = [10, 20, 30], qprofiles = [7], qfrom = [2], qto = [2]
Output: [60]Three events on the same day add up to 60 minutes.
Input: profiles = [4], days = [10], minutes = [50], qprofiles = [5, 4], qfrom = [0, 11], qto = [999, 20]
Output: [0, 0]Profile 5 has no events, and the second window starts after the only event of profile 4. Both totals are 0.
1 ≤ profiles.length ≤ 100,000 (events); days and minutes have the same length1 ≤ profiles[i] ≤ 1,000,000 (profile ids), 0 ≤ days[i] ≤ 999, 1 ≤ minutes[i] ≤ 1,4401 ≤ qprofiles.length ≤ 100,000 (queries); qfrom and qto have the same length1 ≤ qprofiles[q] ≤ 1,000,000, and 0 ≤ qfrom[q] ≤ qto[q] ≤ 999Scanning every event for every query costs n × q, about 10^10 steps. A table with one cell per profile and day would hold 10^9 cells, which is too large, and most cells would be empty. Sorting the sparse events once and answering each query by two binary searches and one subtraction costs about (n + q) log n.