Prefix sum · Hard
An audit dashboard asks for account-range balances at many historical times. Replaying all ledger entries for every query is too expensive.
Answer inclusive account-range sums using entries at or before each query time.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ accounts:integer, entries:{account:integer,time:integer,cents:integer}[], queries:{time:integer,left:integer,right:integer}[] }
What each field means
accounts— number of accounts with IDs0throughaccounts - 1.entries— signed balance adjustments withaccount,timeandcents.queries— a historicaltimeand inclusive account boundsleftandright.
Output
Return value and rules
- Return one integer sum per query in the original query order.
- Include adjustments whose account is between
leftandrightand whose time is at or before the query time. - Add adjustments together; a later entry does not replace an earlier balance.
Constraints
- 1 <= accounts <= 100000; entries.length and queries.length <= 100000
- 0 <= account < accounts; 0 <= left <= right < accounts; time in [0,1000000000]; cents in [-1000000,1000000]
- Entries are adjustments, not replacement balances; equal-time entries are all included.
Examples
Example 1
{
"accounts": 2,
"entries": [
{
"account": 0,
"time": 1,
"cents": 5
},
{
"account": 1,
"time": 3,
"cents": 7
}
],
"queries": [
{
"time": 3,
"left": 0,
"right": 1
},
{
"time": 1,
"left": 0,
"right": 1
}
]
}Returns
[
12,
5
]Example 2
{
"accounts": 1,
"entries": [],
"queries": []
}Returns
[]Required complexity
O((e + q) log(e + q) + (e + q) log accounts) time and O(accounts + e + q) space