Skip to the code
cf.
+25 XP

#725 Visible Rows with Mixed Heights

medium

A chat app virtualizes its message list. Messages have different heights: heights[i] is the height of message i in pixels. Message 0 starts at pixel 0, and each message starts where the previous one ends.

The view shows pixels from scrollTop up to (not including) scrollTop + viewportHeight. A message is visible if it shares at least one pixel with the view. Write visibleRange(heights, scrollTop, viewportHeight) that returns [first, last], the first and last visible message indexes, or an empty array if none is visible.

The list can have 100,000 messages and this runs on every scroll event, so find first faster than a scan from the top.

Example 1

Input: heights = [40,60,30,50,40,80], scrollTop = 70, viewportHeight = 100
Output: [1,3]

Messages start at 0, 40, 100, 130, 180. Pixels 70 to 169 touch messages 1, 2, and 3.

Example 2

Input: heights = [40,60,30], scrollTop = 500, viewportHeight = 100
Output: []

The view is below the last message.

Constraints

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