37 · Design Data Structures

#895 Maximum Frequency Stack

Hardsolve on LeetCode ↗

frequently reported atAmazonMicrosoftGoogle

the problem

In plain words

Design FreqStack, a stack with a twist. push(val) puts val on top as usual. pop() removes and returns the value that appears most often in the stack right now; if several values tie, it removes the copy of the one closest to the top. pop is only called when the stack is not empty.

in push(5), push(7), push(5), push(7), push(4), push(5), pop(), pop(), pop(), pop()

out 5, 7, 5, 4

First 5 is the most frequent (3 copies). Then 5 and 7 tie at 2, and the 7 is nearer the top. Then 5 (2 copies). Then 4, 5 and 7 tie at 1, and 4 is nearest the top.

  • 0 ≤ val ≤ 10⁹
  • At most 2·10⁴ calls to push and pop
  • pop is only called on a non-empty stack

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #155
      Min Stack
      Mediumin Stacks
    2. #347
    3. #380