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 integer val 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.

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
Maximum Frequency Stack: Push and Pop by FrequencyPush Sequence575745Frequency Analysis5: freq=37: freq=24: freq=1Max frequencySecond highestLowestPop Order: Always remove most frequent element (tie-break by recency)5754Pop Sequence: [5, 7, 5, 4]Optimal: O(1) push/pop using frequency-level stacks
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.5K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen