VOOZH about

URL: https://www.geeksforgeeks.org/dsa/design-a-stack-which-can-give-maximum-frequency-element/

⇱ Design a stack with max frequency element operation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Design a stack with max frequency element operation

Last Updated : 2 Nov, 2024

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)  

Naive Approach - Priority Queue and Hash Map

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).


Output
6
8

Time Complexity: O(Log (n)) on average'
Auxiliary Space: O(n)

Expected Approach - Using Two Hash Maps or Dictionaries

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:  

  1. push(int x): map the element (x) with frequency HashMap and update the maxfreq variable ( i.e. holds the maximum frequency till now ). setMap maintains a stack which contains all the elements with same frequency.
  2. pop(): First get the maxfreq element from setMap and then decrement the frequency of the popped element. After popping, if the stack becomes empty then decrement the maxfreq. 

Output
6
8

Time Complexity: O(1) on average for both push() and pop()
Auxiliary Space: O(n)


Comment
Article Tags: