Maximum Frequency Stack
Difficulty: Hard · Pattern: Stack & Monotonic Stack · LeetCode #895
Design FreqStack:
push(val): push an integer.pop(): remove and return the most frequent element; on ties, the one pushed most recently.
Example
text
push 5, 7, 5, 7, 4, 5 → pop() = 5, pop() = 7, pop() = 5, pop() = 4Hints
- Track each value's frequency.
- Keep a separate stack for each frequency level: when a value reaches frequency f, push it onto stack f.
- pop takes from the highest non-empty level.
Approach
freq[val] holds counts; group[f] is a stack of values that reached frequency f (in push order); maxf is the current maximum frequency. push: increment freq, push onto group[freq], update maxf. pop: pop from group[maxf], decrement that value's frequency, and if the level is empty, decrement maxf. A value appears in every level up to its frequency, which preserves the tie-breaking order. O(1) per operation.
Complexity
Time: O(1) per operation. Space: O(n).
Python solution
from collections import defaultdict
class FreqStack:
def __init__(self):
self.freq = defaultdict(int)
self.group = defaultdict(list)
self.maxf = 0
def push(self, val):
self.freq[val] += 1
f = self.freq[val]
self.maxf = max(self.maxf, f)
self.group[f].append(val)
def pop(self):
val = self.group[self.maxf].pop()
self.freq[val] -= 1
if not self.group[self.maxf]:
self.maxf -= 1
return valJavaScript solution
class FreqStack {
constructor() { this.freq = new Map(); this.group = new Map(); this.maxf = 0; }
push(val) {
const f = (this.freq.get(val) || 0) + 1; this.freq.set(val, f);
this.maxf = Math.max(this.maxf, f);
if (!this.group.has(f)) this.group.set(f, []);
this.group.get(f).push(val);
}
pop() {
const g = this.group.get(this.maxf), val = g.pop();
this.freq.set(val, this.freq.get(val) - 1);
if (!g.length) this.maxf--;
return val;
}
}