Skip to the code
cf.
+25 XP

#275 Price Stack With Instant Minimum

medium

A pricing editor lets you try price changes and undo them, last one first. It also shows the lowest price among all changes still applied. Write a class PriceStack:

  • push(price) applies a change.
  • pop() undoes the most recent change and returns nothing.
  • top() returns the most recent price.
  • getMin() returns the lowest price currently in the stack.

Every method must run in O(1) time. pop, top, and getMin are only called when the stack is not empty.

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

Example 1

Input: ["PriceStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]

The minimum is -3 until it is popped; then the top is 0 and the minimum is -2.

Example 2

Input: ["PriceStack","push","top","getMin"]
[[],[7],[],[]]
Output: [null,null,7,7]

With one price, it is both the top and the minimum.

Constraints

  • -2^31 <= price <= 2^31 - 1
  • At most 3 * 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).