Maximum Frequency Stack - 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 integervalonto 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.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"], values = [null, 5, 7, 5, 7, 4, 5, null, null, null, null]
›
Output:
[null, null, null, null, null, null, null, 5, 7, 5, 4]
💡 Note:
After pushes: 5(freq=3), 7(freq=2), 4(freq=1). Pop returns most frequent: 5, then 7, then 5, then 4.
Example 2 — Tie Breaking
$
Input:
operations = ["FreqStack", "push", "push", "push", "pop", "pop"], values = [null, 1, 2, 3, null, null]
›
Output:
[null, null, null, null, 3, 2]
💡 Note:
All elements have frequency 1, so pop returns most recent: 3, then 2.
Example 3 — Same Element Multiple Times
$
Input:
operations = ["FreqStack", "push", "push", "pop", "pop"], values = [null, 1, 1, null, null]
›
Output:
[null, null, null, 1, 1]
💡 Note:
Push 1 twice (freq=2), pop returns 1 (freq becomes 1), pop returns 1 again.
Constraints
- 1 ≤ val ≤ 109
- At most 2 × 104 calls to push and pop
- It is guaranteed that there will be at least one element in the stack before calling pop
Visualization
Tap to expand
Understanding the Visualization
1
Input
Push operations: 5, 7, 5, 7, 4, 5
2
Process
Track frequencies and organize in frequency stacks
3
Output
Pop most frequent elements: 5, 7, 5, 4
Key Takeaway
🎯 Key Insight: Group elements by frequency in separate stacks for instant O(1) access to maximum frequency elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code