Skip to the code
cf.
+10 XP

#276 Layer Stack With Highest Z-Index

easy

A design tool opens nested overlays (menus, dialogs, tooltips) as a stack, and each overlay has a z-index. To place a new overlay above everything, the tool needs the highest z-index still open. Write a class LayerStack:

  • push(z) opens an overlay with z-index z.
  • pop() closes the newest overlay and returns its z-index.
  • top() returns the newest overlay's z-index.
  • peekMax() returns the highest z-index among the open overlays.

Every method must run in O(1) time. pop, top, and peekMax are only called when at least one overlay is open.

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

Example 1

Input: ["LayerStack","push","push","push","peekMax","pop","peekMax","top"]
[[],[10],[50],[20],[],[],[],[]]
Output: [null,null,null,null,50,20,50,50]

50 stays the highest until it is closed; closing 20 doesn't change it.

Example 2

Input: ["LayerStack","push","peekMax","pop"]
[[],[3],[],[]]
Output: [null,null,3,3]

One overlay is both the newest and the highest.

Constraints

  • -10^7 <= z <= 10^7
  • At most 10^4 calls.
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).