Maximum Frequency Stack

Design a stack-like structure that pops the most frequent element. - `FreqStack()` creates an empty frequency stack. - `void push(int val)` pushes `val` on top. - `int pop()` removes and returns the most frequent element in the stack. If several elements tie for the highest frequency, the one closest to the top (pushed most recently) is removed and returned.

30:00

Maximum Frequency Stack
hard
Free written solution
Topics
Companies

Design a stack-like structure that pops the most frequent element.

  • FreqStack() creates an empty frequency stack.
  • void push(int val) pushes val on top.
  • int pop() removes and returns the most frequent element in the stack. If several elements tie for the highest frequency, the one closest to the top (pushed most recently) is removed and returned.
Example 1:
Input: {"commands":["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],"values":[[],[5],[7],[5],[7],[4],[5],[],[],[],[]]}
Output: [null,null,null,null,null,null,null,5,7,5,4]
Constraints:
  • 0≤val≤1090 \leq \text{val} \leq 10^9

  • At most 2×1042 \times 10^4 calls are made to push and pop.

  • pop is only called when the stack holds at least one element.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],"values":[[],[5],[7],[5],[7],[4],[5],[],[],[],[]]}
new()
push(5)
push(7)
push(5)
push(7)
push(4)
push(5)
pop()
pop()

…

Empty structure. freq counts each value; group[f] is a stack of values in the order they reached count f. Popping the top of group[maxfreq] gives the most frequent, most recent value.

group[f]: one stack per frequency level

maxfreq = 0

empty

a value seen 3 times sits on levels 1, 2 and 3; pop always takes the top of the highest level

freq (value: count)

empty

Returned values

[null]
Variables
VariableValue
maxfreq0
DepthFunction Call
Stack empty
0/21