File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments