Skip to the code
cf.
+10 XP

#726 Scroll a Row into View

easy

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:

  • If the row's top is above the view, scroll so the row's top is at the top of the view.
  • Otherwise, if the row's bottom is below the view, scroll so the row's bottom is at the bottom of the view; but if the row is taller than the view, align its top instead.
  • Otherwise the row is fully visible: keep scrollTop.

Example 1

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.

Example 2

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.

Constraints

  • 1 <= heights.length <= 10^5, 1 <= heights[i] <= 10^4
  • 0 <= index < heights.length
  • 0 <= scrollTop <= 10^9, 1 <= viewportHeight <= 10^4
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).