Skip to content

Commit f572c37

Browse files
committed
Solution as on 20-03-2022 08:22 am
1 parent 49f9bb7 commit f572c37

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

0895. Maximum Frequency Stack.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// 895.✅ Maximum Frequency Stack
2+
3+
class FreqStack
4+
{
5+
public:
6+
// freqMap is to map element to its frequency
7+
map<int, int> freqMap;
8+
9+
// set map is to map frequency to the
10+
// element list with this frequency
11+
map<int, stack<int>> setMap;
12+
13+
// for keeping record of maximum frequency
14+
int maxfreq = 0;
15+
16+
FreqStack()
17+
{
18+
// KNOCKCAT
19+
}
20+
21+
// insert
22+
void push(int val)
23+
{
24+
// frequency of x
25+
int freq = freqMap[val] + 1;
26+
27+
// Mapping of x with its frequency
28+
freqMap[val] = freq;
29+
30+
// if freq is greater than maxfreq
31+
// update max freq
32+
if (freq > maxfreq)
33+
maxfreq = freq;
34+
35+
// Mapping element to its frequency list
36+
setMap[freq].push(val);
37+
}
38+
39+
// remove
40+
int pop()
41+
{
42+
// remove element from setMap
43+
// from maximum frequency list
44+
int top = setMap[maxfreq].top();
45+
setMap[maxfreq].pop();
46+
47+
// decrement the frequcy of the popped element
48+
--freqMap[top];
49+
50+
// if whole list popped decrement the max freq
51+
if (setMap[maxfreq].size() == 0)
52+
--maxfreq;
53+
return top;
54+
}
55+
};

0 commit comments

Comments
 (0)