When you press the down arrow in a long virtualized list, the selected row must become visible, scrolling as little as possible, like element.scrollIntoView({ block: "nearest" }).
Rows have heights heights and are stacked from pixel 0. The view shows viewportHeight pixels starting at scrollTop. Write scrollToRow(heights, index, scrollTop, viewportHeight) that returns the new scrollTop:
scrollTop.Input: heights = [30,30,30,30,30,30], index = 5, scrollTop = 0, viewportHeight = 100 Output: 80
Row 5 spans pixels 150 to 180, so the view must end at 180 and start at 180 - 100 = 80.
Input: heights = [30,30,30,30,30,30], index = 1, scrollTop = 80, viewportHeight = 100 Output: 30
Row 1 starts at 30, above the view, so the view starts there.
1 <= heights.length <= 10^5, 1 <= heights[i] <= 10^40 <= index < heights.length0 <= scrollTop <= 10^9, 1 <= viewportHeight <= 10^4Run 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).
I'm here to help with #726 Scroll a Row into View. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.