HardNo. 0895
Maximum Frequency Stack — LeetCode 895 Python Solution
- Pattern
- Stack
- Topics
- Stack, Design, Hash Table, Ordered Set
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
- Output
- [null, null, null, null, null, null, null, 5, 7, 5, 4]
- Explanation
- FreqStack freqStack = new FreqStack();
Python solution
class FreqStack:
def __init__(self):
self.cnt = defaultdict(int)
self.q = []
self.ts = 0
def push(self, val: int) -> None:
self.ts += 1
self.cnt[val] += 1
heappush(self.q, (-self.cnt[val], -self.ts, val))
def pop(self) -> int:
val = heappop(self.q)[2]
self.cnt[val] -= 1
return val
# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(val)
# param_2 = obj.pop()Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 895. Maximum Frequency Stack is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0352 | Data Stream as Disjoint Intervals | Hard |
| 1172 | Dinner Plate Stacks | Hard |
| 1348 | Tweet Counts Per Frequency | Medium |
| 1912 | Design Movie Rental System | Hard |
| 2034 | Stock Price Fluctuation | Medium |
| 2336 | Smallest Number in Infinite Set | Medium |
Frequently asked questions
- How hard is LeetCode 895. Maximum Frequency Stack?
LeetCode 895. Maximum Frequency Stack is rated Hard on LeetCode.
- What is the time complexity of LeetCode 895. Maximum Frequency Stack?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 895. Maximum Frequency Stack?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 895. Maximum Frequency Stack cover?
LeetCode 895. Maximum Frequency Stack is tagged Stack, Design, Hash Table and Ordered Set on LeetCode.