Problem
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the FreqStack
class:
FreqStack()
constructs an empty frequency stack.void push(int val)
pushes an integerval
onto the top of the stack.int pop()
removes and returns the most frequent element in the stack.- If there is a tie for the most frequent element, the element closest to the stack’s top is removed and returned.
Examples
Example 1:
|
|
Solution
Method 1 – Heap and HashMap
Intuition
To efficiently return the element with the highest frequency, we use a hash map to track the frequency of each element. To resolve ties (when multiple elements have the same frequency), we use a heap that prioritizes elements by frequency and, in case of a tie, by the time they were pushed (most recent first).
Approach
- Use a hash map to store the frequency of each element.
- Use a max heap (priority queue) to store nodes containing the value, its frequency, and the time it was pushed.
- When pushing, increment the frequency and add a node to the heap with the current time.
- When popping, remove the node with the highest frequency (and most recent if tied) and decrement its frequency in the hash map.
Complexity
- ⏰ Time complexity:
O(log n)
for both push and pop, as each operation involves insertion or removal from the heap. - 🧺 Space complexity:
O(n)
, for storing frequencies and heap nodes.
C++
|
|
Java
|
|
Python
|
|
Method 2 – Hashmap of Frequency and Stack
Intuition
To quickly access and remove the most frequent element, we use a hash map to track the frequency of each value and another hash map to group values by their frequency using stacks. The stack for each frequency ensures that the most recently added element with that frequency is popped first, resolving ties by recency.
Approach
- Maintain a hash map to count the frequency of each value.
- Use another hash map to map each frequency to a stack of values with that frequency.
- Track the current maximum frequency.
- On push, increment the value’s frequency, update the max frequency, and push the value onto the corresponding frequency stack.
- On pop, remove and return the top value from the max frequency stack, decrement its frequency, and update max frequency if needed.
Complexity
- ⏰ Time complexity:
O(1)
for both push and pop, as all operations are direct hash map and stack accesses. - 🧺 Space complexity:
O(n)
, for storing frequencies and stacks.
C++
|
|
Java
|
|
Python
|
|