SDE & MLE Prep

895. Maximum Frequency Stack

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