Problem 261817 · easy · Level 02 Linear Data Structures

A Crate Stack That Knows Its Extremes

stacks · class design

Warehouse crates are stacked one on top of another, and only the top crate can be added or lifted off. The foreman also wants to know, at any moment, the lightest and the heaviest crate in the pile without unstacking it. Write the class BoundsStack for integer crate weights, where every operation takes constant time:

  • BoundsStack(): start with no crates.
  • push(x): put a crate weighing x on top.
  • pop(): lift the top crate off and return its weight.
  • top(): return the top crate's weight, leaving it in place.
  • min_val(): return the lightest weight in the pile.
  • max_val(): return the heaviest weight in the pile.

pop, top, min_val and max_val are only called while at least one crate is stacked.

Examples

Input:  ops  = ["BoundsStack", "push", "push", "push", "min_val", "max_val", "pop", "min_val", "max_val", "top"]
        args = [[], [4], [9], [1], [], [], [], [], [], []]
Output: [None, None, None, None, 1, 9, 1, 4, 9, 9]
Explanation: after pushing 4, 9, 1 the min is 1 and max is 9; popping the 1 makes the min 4 again.

Constraints

  • At most 2 * 10**4 operations
  • Target: O(1) per operation

Goals

  • Store extra bookkeeping alongside each pushed value
  • Answer min and max in O(1) without scanning the stack
Starting Python…