Skip to the code
cf.
+10 XP

#662 Topmost Layer Under the Cursor

easy

A design tool stacks layers. layers lists each layer's box { x, y, width, height } from bottom to top, so a later layer is drawn above earlier ones.

Write layerAt(layers, px, py) that returns the index of the topmost layer containing the point (px, py), or -1 if no layer contains it. A box contains a point when x <= px < x + width and y <= py < y + height: the left and top edges count, the right and bottom edges don't.

Example 1

Input: layers = [{"x":0,"y":0,"width":100,"height":100},{"x":20,"y":20,"width":30,"height":30}], px = 25, py = 25
Output: 1

Both layers contain the point, and layer 1 is drawn on top.

Example 2

Input: layers = [{"x":0,"y":0,"width":100,"height":100},{"x":20,"y":20,"width":30,"height":30}], px = 60, py = 60
Output: 0

Only the big background layer contains (60, 60).

Constraints

  • 0 <= layers.length <= 10^4
  • All values are whole numbers between -10^4 and 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).