Dsa
Heap
Medium
Max Frequency Stack
Implement a frequency stack that supports the following operations: push(int x), pop(). Each time you push an element, it should be stored in a stack based on its frequency. When you pop, you should return the most frequent element (among the elements that are at the highest frequency). If there's a tie, return the element that was pushed most recently.
Input Format:
- The first line contains an integer Q (1 <= Q <= 10000), the number of queries.
- The next Q lines contain either 'push x' or 'pop'.
Output Format:
- For each 'pop' operation, print the result. If pop is called on an empty stack, print 'Empty'.
Example:
Input:
8
push 5
push 7
push 5
push 7
push 4
pop
pop
pop
Output:
5
7
7
Key concepts
heapfrequencystack
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now