Maximum Frequency Stack in C++

C++Server Side ProgrammingProgramming

Suppose we want to implement one stack called FreqStack, Our FreqStack has two functions −

  • push(x), This will push an integer x onto the stack.

  • pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned.

So, if the input is like push some elements like 7, 9, 7, 9, 6, 7, then perform the pop operations four times, then the output will be 7,9,7,6 respectively.

To solve this, we will follow these steps −

  • Define one map cnt

  • Define one map sts

  • maxFreq := 0

  • Define a function push(), this will take x,

  • (increase cnt[x] by 1)

  • maxFreq := maximum of maxFreq and cnt[x]

  • insert x into sts[cnt[x]]

  • Define a function pop()

  • maxKey := maxFreq

  • x := top element of sts[maxKey]

  • delete element from sts[maxKey]

  • if size of sts[maxKey] is same as 0, then −

    • delete maxKey from sts

    • (decrease maxFreq by 1)

  • (decrease cnt[x] by 1)

  • return x

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class FreqStack {
   public:
   unordered_map <int ,int > cnt;
   unordered_map <int, stack <int> >sts;
   int maxFreq = 0;
   FreqStack() {
      maxFreq = 0;
      cnt.clear();
      sts.clear();
   }
   void push(int x) {
      cnt[x]++;
      maxFreq = max(maxFreq, cnt[x]);
      sts[cnt[x]].push(x);
   }
   int pop() {
      int maxKey = maxFreq;
      int x = sts[maxKey].top();
      sts[maxKey].pop();
      if(sts[maxKey].size() == 0){
         sts.erase(maxKey);
         maxFreq--;
      }
      cnt[x]--;
      return x;
   }
};
main(){
   FreqStack ob;
   ob.push(7);
   ob.push(9);
   ob.push(7);
   ob.push(9);
   ob.push(6);
   ob.push(7);
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
}

Input

push elements 7, 9, 7, 9, 6, 7, then call pop() four times.

Output

7
9
7
6
raja
Published on 04-Jun-2020 08:52:38
Advertisements