Maximum Frequency Stack — LeetCode 895 Python Solution

HardStackDesignHash TableOrdered Set
Problem
#895
Pattern
Stack
Reading time
4 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview