Program to construct Frequency Stack in C++


Suppose we want to construct one stack called FrequencyStack, Our FrequencyStack has two functions −

  • append(x), This will append or push a value 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 the same frequency, then the element closest to the top of the stack is removed and returned.

So, if the input is like append 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 append(), 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 append(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.append(7);
   ob.append(9);
   ob.append(7);
   ob.append(9);
   ob.append(6);
   ob.append(7);
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
}

Input

ob.append(7);
ob.append(9);
ob.append(7);
ob.append(9);
ob.append(6);
ob.append(7);
cout << (ob.pop()) << endl;
cout << (ob.pop()) << endl;
cout << (ob.pop()) << endl;
cout << (ob.pop()) << endl;

Output

7
9
7
6

Updated on: 26-Dec-2020

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements