#895
Hard Algorithms Maximum frequency stack
Hash Table Stack Design Ordered Set
66.6% acceptance
Feb 22, 2026
4937
78
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.
Solution
Rust
Time O(2^n)
Space O(n)
* impl FreqStack {
* fn new() -> Self {
* }
* fn push(&self, val: i32) {
* }
* fn pop(&self) -> i32 {
* }
* }
*/
/**
* Your FreqStack object will be instantiated and called as such:
* let obj = FreqStack::new();
* obj.push(val);
* let ret_2: i32 = obj.pop();
*/
use std::collections::HashMap;
struct FreqStack {
freq: HashMap<i32, i32>,
group: HashMap<i32, Vec<i32>>,
max_freq: i32,
}
impl FreqStack {
fn new() -> Self {
FreqStack { freq: HashMap::new(), group: HashMap::new(), max_freq: 0 }
}
fn push(&mut self, val: i32) {
let f = self.freq.entry(val).or_insert(0);
*f += 1;
let f = *f;
if f > self.max_freq { self.max_freq = f; }
self.group.entry(f).or_default().push(val);
}
fn pop(&mut self) -> i32 {
let val = self.group.get_mut(&self.max_freq).unwrap().pop().unwrap();
if self.group.get(&self.max_freq).map_or(true, |s| s.is_empty()) {
self.group.remove(&self.max_freq);
self.max_freq -= 1;
}
*self.freq.get_mut(&val).unwrap() -= 1;
val
}
}