![]() |
VOOZH | about |
Given n elements and the task is to implement a stack which removes and returns the maximum frequency element on every pop operation. If there's a tie in the frequency then the topmost highest frequency element will be returned.
Examples:
Input:
push(4) 8
push(6) 6
push(7) 7
push(6) 6
push(8); 4
Output:
pop() -> returns 6, as 6 is the most frequent (frequency of 6 = 2 ).
pop() -> returns 8 (6 also has the highest frequency but it is not the topmost)
The idea is to use priority queue to order elements by frequency and a hash map to store frequencies of items.
push(x) : We increment frequency in map and insert new frequency in the priority queue.
pop(): We pop the top item from priority queue (which is the max frequency item).
6 8
Time Complexity: O(Log (n)) on average'
Auxiliary Space: O(n)
One is frequency Hash Map which maps elements to their frequencies and other is setMap which maps all the element with same frequency in one group (Stack).
FrequencyStack has 2 functions:
6 8
Time Complexity: O(1) on average for both push() and pop()
Auxiliary Space: O(n)