Skip to the code
cf.
+50 XP

#728 Row Offsets with Live Updates

hard

A huge virtualized spreadsheet keeps row heights that change as rows are measured or resized. Recomputing all running totals after each change is too slow, so build a structure that handles both.

Implement RowOffsets: new RowOffsets(heights) starts with the given heights. setHeight(index, height) changes one row's height. offsetOf(index) returns the pixel where row index starts (the sum of the heights before it). rowAt(y) returns the index of the row that contains pixel y (a row covers from its offset up to, not including, its offset plus its height), or -1 if y is negative or not inside any row. total() returns the sum of all heights.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new RowOffsets(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["RowOffsets","offsetOf","rowAt","setHeight","offsetOf","rowAt","total"]
[[[40,60,30,50]],[2],[99],[1,10],[2],[99],[]]
Output: [null,100,1,null,50,3,130]

Row 2 starts at 40 + 60 = 100, and pixel 99 is in row 1. After row 1 shrinks to 10, row 2 starts at 50 and pixel 99 is in row 3 (pixels 80 to 129).

Constraints

  • 1 <= heights.length <= 10^5, heights are whole numbers from 1 to 10^4.
  • Up to 10^5 method calls in total; each must be about O(log n).
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).