Skip to main content
LeetCode 895, Hard. Topics: Hash Table, Stack, Design, Ordered Set. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

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 the 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.

Examples

Explanation:

Constraints

  • 0 <= val <= 10^9
  • At most 2 * 10^4 calls will be made to push and pop.
  • It is guaranteed that there will be at least one element in the stack before calling pop.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Grind, NeetCode 250, NeetCode All.
Last modified on August 25, 2026