[LeetCode] Maximum Frequency Stack

895. Maximum Frequency Stack

Implement FreqStack, a class which simulates the operation of a stack-like data structure.

FreqStack has two functions:

  • push(int x), which pushes an integer x onto the stack.
  • pop(), which removes and returns the most frequent element in the stack.
  • If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class FreqStack {
unordered_map<int, list<int>> m;
map<int, list<int>> sizeMap;
int cnt = 0;
public:
FreqStack() {
}
void push(int x) {
m[x].push_back(cnt++);
sizeMap[(int)m[x].size()].push_back(x);
}

int pop() {
auto res = rend(sizeMap)->second.back();
sizeMap[(int)m[res].size()].pop_back();
if(sizeMap[(int)m[res].size()].empty())
sizeMap.erase((int)m[res].size());
m[res].pop_back();
return res;
}
};

/**
* Your FreqStack object will be instantiated and called as such:
* FreqStack* obj = new FreqStack();
* obj->push(x);
* int param_2 = obj->pop();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/01/PS/LeetCode/maximum-frequency-stack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.