Maximum Frequency Stack
Maximum Frequency Stack is a hard design data structures problem solved with the stack pattern.
The best approach, optimal (stack per frequency level), runs in O(1) per operation time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from heap with (frequency, push time) up.
Problem
Design a stack where pop removes and returns the most frequent element. If several elements are equally frequent, it removes the one closest to the top (pushed most recently).
Examples
Example 1
- Input
push 5, 7, 5, 7, 4, 5; pop(); pop(); pop(); pop()- Output
5, 7, 5, 4- Why
- 5 (freq 3) → then 5 and 7 tie at 2, and 7 is closer to the top → then 5 → then 4, 7 tie at 1 and 4 is closer to the top.
Constraints
- Up to 2 · 10^4 calls; pop is only called on a non-empty stack.
- pop removes the most frequent element; ties go to the one pushed most recently.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (1 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Heap with (frequency, push time) | O(log n) per operation | O(n) |
| Optimal (stack per frequency level) | O(1) per operation | O(n) |
1Heap with (frequency, push time)
O(log n) per operationO(n)Push entries {value, frequency after push, timestamp} into a max-heap ordered by frequency, then by timestamp. Popping takes the heap top and lowers that value's frequency.
- push: freq[v]++; heap.add({v, freq[v], time++}).
- pop: e = heap.poll(); freq[e.v]--; return e.v.
class FreqStack {
private final Map<Integer, Integer> freq = new HashMap<>();
private final PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[1] != b[1] ? b[1] - a[1] : b[2] - a[2]);
private int time = 0;
public void push(int val) {
int f = freq.merge(val, 1, Integer::sum);
heap.add(new int[] { val, f, time++ });
}
public int pop() {
int v = heap.poll()[0];
freq.merge(v, -1, Integer::sum);
return v;
}
}class FreqStack:
def __init__(self):
self.freq = defaultdict(int)
self.heap = []
self.time = 0
def push(self, val: int) -> None:
self.freq[val] += 1
f = self.freq[val]
heapq.heappush(self.heap, (-f, -self.time, val))
self.time += 1
def pop(self) -> int:
v = heapq.heappop(self.heap)[2]
self.freq[v] -= 1
return vclass FreqStack {
unordered_map<int, int> freq;
priority_queue<array<int, 3>> heap; // {frequency, push time, val}, max-heap
int time = 0;
public:
void push(int val) {
int f = ++freq[val];
heap.push({ f, time++, val });
}
int pop() {
int v = heap.top()[2];
heap.pop();
freq[v]--;
return v;
}
};class FreqStack {
constructor() {
this.freq = new Map();
this.heap = []; // binary heap ordered by (frequency desc, push time desc)
this.time = 0;
}
higher(a, b) { return a[1] !== b[1] ? a[1] > b[1] : a[2] > b[2]; }
push(val) {
const f = (this.freq.get(val) || 0) + 1;
this.freq.set(val, f);
const h = this.heap;
h.push([val, f, this.time++]);
let i = h.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.higher(h[i], h[p])) break;
[h[i], h[p]] = [h[p], h[i]];
i = p;
}
}
pop() {
const h = this.heap;
const top = h[0];
const last = h.pop();
if (h.length > 0) {
h[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < h.length && this.higher(h[l], h[m])) m = l;
if (r < h.length && this.higher(h[r], h[m])) m = r;
if (m === i) break;
[h[i], h[m]] = [h[m], h[i]];
i = m;
}
}
const v = top[0];
this.freq.set(v, this.freq.get(v) - 1);
return v;
}
}2Optimal (stack per frequency level)
O(1) per operationO(n)group[f] is a stack of values that reached frequency f, in push order. Pushing v with new frequency f adds it to group[f]. Earlier copies stay in lower groups, which is correct: after popping, v's frequency drops by one and its lower copy is still in the right place.
- push: f = ++freq[v]; maxFreq = max(maxFreq, f); group[f].push(v).
- pop: v = group[maxFreq].pop(); freq[v]--; if the group is empty, maxFreq--.
class FreqStack {
private final Map<Integer, Integer> freq = new HashMap<>();
private final Map<Integer, Deque<Integer>> group = new HashMap<>();
private int maxFreq = 0;
public void push(int val) {
int f = freq.merge(val, 1, Integer::sum);
maxFreq = Math.max(maxFreq, f);
group.computeIfAbsent(f, k -> new ArrayDeque<>()).push(val);
}
public int pop() {
int v = group.get(maxFreq).pop();
freq.merge(v, -1, Integer::sum);
if (group.get(maxFreq).isEmpty()) maxFreq--;
return v;
}
}class FreqStack:
def __init__(self):
self.freq = defaultdict(int)
self.group = defaultdict(list)
self.maxFreq = 0
def push(self, val: int) -> None:
self.freq[val] += 1
f = self.freq[val]
self.maxFreq = max(self.maxFreq, f)
self.group[f].append(val)
def pop(self) -> int:
v = self.group[self.maxFreq].pop()
self.freq[v] -= 1
if not self.group[self.maxFreq]:
self.maxFreq -= 1
return vclass FreqStack {
unordered_map<int, int> freq;
unordered_map<int, stack<int>> group;
int maxFreq = 0;
public:
void push(int val) {
int f = ++freq[val];
maxFreq = max(maxFreq, f);
group[f].push(val);
}
int pop() {
int v = group[maxFreq].top();
group[maxFreq].pop();
freq[v]--;
if (group[maxFreq].empty()) maxFreq--;
return v;
}
};class FreqStack {
constructor() {
this.freq = new Map();
this.group = new Map();
this.maxFreq = 0;
}
push(val) {
const f = (this.freq.get(val) || 0) + 1;
this.freq.set(val, f);
this.maxFreq = Math.max(this.maxFreq, f);
if (!this.group.has(f)) this.group.set(f, []);
this.group.get(f).push(val);
}
pop() {
const v = this.group.get(this.maxFreq).pop();
this.freq.set(v, this.freq.get(v) - 1);
if (this.group.get(this.maxFreq).length === 0) this.maxFreq--;
return v;
}
}Edge cases to test
- Ties in frequency
- Pushing a value again after it was popped
Hints
Hint 1
Keep a separate stack for each frequency level. A value pushed for the 3rd time goes on stack 3. Pop from the highest non-empty level.
FAQ
What is the best time complexity for Maximum Frequency Stack?
Optimal (stack per frequency level) runs in O(1) per operation time and O(n) extra space.
Which pattern does Maximum Frequency Stack use?
It is a design data structures problem that uses the stack pattern. Other problems with the same pattern: Min Stack, Design a Stack With Increment Operation, Max Stack.
Is there a brute force solution for Maximum Frequency Stack?
Yes. Heap with (frequency, push time) takes O(log n) per operation time and O(n) space. Push entries {value, frequency after push, timestamp} into a max-heap ordered by frequency, then by timestamp.
Which edge cases should I test for Maximum Frequency Stack?
Ties in frequency; Pushing a value again after it was popped.