Problem Description
Design a stack-like data structure that supports push and pop operations. The pop operation removes and returns the most frequent element in the stack. In case of a tie (i.e. multiple elements have the same frequency), the element closest to the top of the stack is removed and returned.
Key Insights
- Use a hash map to count the frequency of each element.
- Maintain another hash map that maps frequencies to stacks (lists) of elements.
- Track the current maximum frequency to enable O(1) retrieval of the most frequent element.
- When pushing an element, update its frequency and add it to the corresponding frequency stack.
- When popping an element, remove it from the stack corresponding to the maximum frequency and update the frequency count; if that stack becomes empty, decrease the current maximum frequency.
Space and Time Complexity
Time Complexity: O(1) per push and pop. Space Complexity: O(n), where n is the number of elements pushed onto the stack.
Solution
The solution involves using two main data structures:
- A hash map (freq) to store the frequency count for each value.
- A hash map (group) that maps a frequency to a stack (list) of values that have that frequency.
During a push:
- Increment the frequency count of the value.
- Push the value onto the stack corresponding to its updated frequency.
- Update the maximum frequency if necessary.
During a pop:
- Pop the top element from the stack corresponding to the current maximum frequency.
- Decrement its frequency count in the freq map.
- If the frequency stack becomes empty after popping, decrement the current maximum frequency. This design enables the retrieval of the most frequent element in constant time while dealing with frequency ties by returning the element closest to the top.