Maximum Frequency Stack

Stack returning the most frequent element on pop, ties to the most recent — bucket stacks by frequency.

Hard
Time O(1) per op Space O(N)
LeetCode
3 min read
hash-map stack design

Problem#

Design FreqStack:

  • push(val) — push.
  • pop() — return and remove the most frequent value. Ties broken by most recently pushed.

Examples#

  • After push(5), push(7), push(5), push(7), push(4), push(5), the stack reads [5,7,5,7,4,5]. Pops yield 5, 7, 5, 4, 5, 7.

Constraints#

  • 0 <= val <= 10^9, up to 2 * 10^4 calls.

Hints#

Hint
Maintain one stack per frequency level. On push, append to stacks[freq[val]++]. On pop, take the top of the deepest stack.

Approach#

Two maps: freq[val] = current count, and a vector of stacks group[k] = values seen at least k times in push order. On push, increment freq[val] to k, then push to group[k]. On pop, take the top of the deepest stack; decrement freq[val]; clean up empty stacks.

Solution#

Maximum Frequency Stack
class FreqStack {
unordered_map<int,int> freq;
vector<stack<int>> group;
public:
void push(int val) {
int k = ++freq[val];
if ((int)group.size() < k) group.emplace_back();
group[k - 1].push(val);
}
int pop() {
int val = group.back().top();
group.back().pop();
if (group.back().empty()) group.pop_back();
--freq[val];
return val;
}
};

Editorial#

The crucial insight: when we push val for the k-th time, we add it to group[k-1] — but val’s earlier copies remain in group[0..k-2]. On pop, we always take from the deepest non-empty stack, which represents the current max frequency. Each operation touches one stack and one map entry — O(1).

Complexity#

  • Time: O(1) amortized per push / pop.
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.