Maximum Frequency Stack

Hard · Stack & Monotonic Stack · about 30 minutes

Asked at Amazon, Google, Apple, Meta, Bloomberg.

Implement FreqStack, a stack whose pop takes out whichever value has been pushed the most times (and not yet popped).

  • FreqStack() starts empty.
  • push(val) adds an integer.
  • pop() removes and returns a value with the highest current count; if several values tie, it takes the

one pushed most recently. pop is never called when the structure is empty.

Related guides