Maximum Frequency Stack LeetCode solution in C++

1
class FreqStack {
2
public:
3
unordered_map<int, int> ump;
4
unordered_map<int, stack<int>> ump_st;
5

6
int cap = 1;
7

8
FreqStack() {
9
ump.clear();
10
ump_st.clear();
11
}
12

13
void push(int val) {
14
// increasing the count
15
if (ump.find(val) != ump.end()) {
16
ump[val]++;
17
} else {
18
ump[val] = 1;
19
}
20

21
// update the highest level
22
if (cap < ump[val]) {
23
cap = ump[val];
24
}
25

26
// push the elements in the stack where it belongs as per height
27
ump_st[ump[val]].push(val);
28
}
29

30
int pop() {
31
int val = ump_st[cap].top();
32
ump_st[cap].pop();
33

34
if (ump_st[cap].size() == 0) {
35
cap--;
36
}
37

38
ump[val]--;
39

40
if (ump[val] == 0) {
41
ump.erase(val);
42
}
43

44
return val;
45
}
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0