895. Maximum Frequency Stack
Asked at 11Apple35Amazon25Microsoft16Bloomberg14Meta8.5Google8.2Nutanix71Salesforce57Expedia54Flipkart43Uber22
Problem
Design FreqStack: push(val) pushes a value, and pop() removes and returns the most frequent value in the stack; among values tied for most frequent, it pops the one pushed most recently.
Example: push 5, 7, 5, 7, 4, 5 → pop() = 5, then 7, then 5, then 4
Constraints: up to 2·10⁴ calls.
Keep freq[val] and one stack per frequency level: when a value reaches frequency f, push it onto group[f] (it stays in the lower levels too). pop takes from group[maxFreq] — the most recent among the most frequent — decrements its frequency, and lowers maxFreq when that level empties.
push 5 7 5 7 4 5 group[1] = [5 7 4] group[2] = [5 7] group[3] = [5]
pop -> 5 (group[3]) pop -> 7 (group[2], newest) pop -> 5 pop -> 4
Complexity: O(1) per operation.
class FreqStack:
def __init__(self):
self.freq = Counter()
self.group = defaultdict(list)
self.maxf = 0
def push(self, val: int) -> None:
f = self.freq[val] + 1
self.freq[val] = f
self.group[f].append(val)
self.maxf = max(self.maxf, f)
def pop(self) -> int:
val = self.group[self.maxf].pop()
self.freq[val] -= 1
if not self.group[self.maxf]:
self.maxf -= 1
return val
fs = FreqStack()
for v in (5, 7, 5, 7, 4, 5):
fs.push(v)
assert [fs.pop(), fs.pop(), fs.pop(), fs.pop()] == [5, 7, 5, 4]
fs.push(9)
assert [fs.pop(), fs.pop(), fs.pop()] == [9, 7, 5]
class FreqStack {
private final Map<Integer, Integer> freq = new HashMap<>();
private final Map<Integer, Deque<Integer>> group = new HashMap<>();
private int maxf = 0;
public void push(int val) {
int f = freq.merge(val, 1, Integer::sum);
group.computeIfAbsent(f, k -> new ArrayDeque<>()).push(val);
maxf = Math.max(maxf, f);
}
public int pop() {
int val = group.get(maxf).pop();
freq.merge(val, -1, Integer::sum);
if (group.get(maxf).isEmpty()) maxf--;
return val;
}
}
type FreqStack struct {
freq map[int]int // value -> current frequency
group map[int][]int // frequency -> stack of values that reached it
maxf int
}
func Constructor() FreqStack {
return FreqStack{freq: map[int]int{}, group: map[int][]int{}}
}
func (this *FreqStack) Push(val int) {
f := this.freq[val] + 1
this.freq[val] = f
this.group[f] = append(this.group[f], val) // val stays in the lower groups too
this.maxf = max(this.maxf, f)
}
func (this *FreqStack) Pop() int {
g := this.group[this.maxf]
val := g[len(g)-1]
this.group[this.maxf] = g[:len(g)-1]
this.freq[val]--
if len(g) == 1 {
this.maxf--
}
return val
}