Fenwick Tree · Hard
A virtualized list receives row-height corrections while the user scrolls. Recomputing every prefix for every event causes long frames.
Apply row-height updates and answer the pixel offset immediately before a requested row.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ heights: integer[], operations: ({type:"set", index:integer, height:integer}|{type:"offset", index:integer})[] }
Input rules
- An offset index may equal heights.length.
What each field means
heights[i]— initial height of rowiin pixels.operations— actions to process from first to last.setreplaces one row height;offsetasks for the position immediately before a row.
Output
Return value and rules
- Return one number for each
offsetoperation, in that operation order. - The offset at index
iis the sum of current heights at indexes0throughi - 1. - Index
0has offset0; indexheights.lengthasks for the total height. setchanges later answers but adds no element to the result.
Constraints
- 1 <= heights.length <= 100000; 0 <= operations.length <= 100000
- Heights are integers in [0,1000000]; set indexes are [0,n-1]; offset indexes are [0,n].
- No input mutation. Prefix totals fit a safe integer.
Examples
Example 1
{
"heights": [
10,
20,
30
],
"operations": [
{
"type": "offset",
"index": 2
},
{
"type": "set",
"index": 0,
"height": 5
},
{
"type": "offset",
"index": 3
}
]
}Returns
[
30,
55
]Example 2
{
"heights": [
0
],
"operations": [
{
"type": "offset",
"index": 0
},
{
"type": "offset",
"index": 1
}
]
}Returns
[
0,
0
]Required complexity
O((n + q) log n) time and O(n) space