Maximum Frequency Stack (LeetCode 895): Solution and Explanation

Hard
Hash Table
Stack
Design
Ordered Set

Design a stack whose pop removes the most frequent value currently inside it. When several values tie for the highest count, pop the one that was pushed most recently.

Intuition

A heap keyed by (count, push time) works, but it costs O(log n) per call and needs care to keep counts in sync. The structure has a much simpler shape once you think in levels.

Number the copies of each value. The first time 5 is pushed it is copy 1, the second time copy 2, and so on. Put copy k on a stack for level k. A value pushed three times now sits on levels 1, 2 and 3, and the highest non-empty level is exactly the highest frequency in the structure.

Every value on the top level has that highest count, and within one level the stack order is push order. So the top of the top level is the most frequent value and, among ties, the most recent one. Popping it removes that value's highest copy, which lowers its count by exactly one, and its lower copies stay where they are.

When the top level becomes empty, the next level down is non-empty, because every value that reached level k also has a copy on level k - 1. So maxfreq only ever moves by one and no search is needed.

Approach: Stack per frequency level

  1. Keep freq, a map from value to its current count, group, a map from count to a stack, and maxfreq.
  2. push(val): set f = freq[val] + 1, store it, raise maxfreq to f if larger, and push val onto group[f].
  3. pop(): pop val from group[maxfreq] and decrement freq[val].
  4. If group[maxfreq] is now empty, decrease maxfreq by one.
  5. Return val.

Step-by-step example

push 5, 7, 5, 7, 4, 5, then pop four times
  1. After the pushes: level 1 = [5, 7, 4], level 2 = [5, 7], level 3 = [5], maxfreq = 3.
  2. pop: top of level 3 is 5. Level 3 is now empty, so maxfreq = 2. Return 5.
  3. pop: top of level 2 is 7 (pushed after the second 5). Return 7; level 2 = [5].
  4. pop: top of level 2 is 5. Level 2 is empty, maxfreq = 1. Return 5.
  5. pop: top of level 1 is 4. Return 4. Output: [5, 7, 5, 4].

Code: Python, Java, C++

1class FreqStack:
2    def __init__(self):
3        self.freq = {}
4        self.group = {}
5        self.maxfreq = 0
6
7    def push(self, val: int) -> None:
8        f = self.freq.get(val, 0) + 1
9        self.freq[val] = f
10        if f > self.maxfreq:
11            self.maxfreq = f
12        self.group.setdefault(f, []).append(val)
13
14    def pop(self) -> int:
15        val = self.group[self.maxfreq].pop()
16        self.freq[val] -= 1
17        if not self.group[self.maxfreq]:
18            self.maxfreq -= 1
19        return val
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1) per call

Each push and pop does a constant number of hash map and stack operations.

Space

O(n)

Each pushed copy lives in exactly one level stack, plus one counter per distinct value.

Other approaches

Priority queue by (count, time) (time O(log n) per call, space O(n))

Push a tuple (count after this push, global push index, value) into a max-heap. Pop takes the heap top and decrements the value's count. It is correct and easy to reason about, but each operation is O(log n).

Scan for the max on every pop (time O(n) per pop, space O(n))

Keep a plain list and, on pop, find the highest count and the latest index with it. Simple but O(n) per pop.

Common mistakes

  • Moving a value from level f to level f + 1 on push. The lower copy must stay put, otherwise popping the top copy loses the value's place at the lower frequency.
  • Searching for the next maxfreq after a level empties. It is always maxfreq - 1, because every value on level k also has a copy on level k - 1.
  • Breaking ties by value instead of by recency. The stack order inside a level already encodes recency.

Frequently asked questions

Why does the top of the highest level break ties correctly?

All values on that level have the same, highest count. They were placed there in the order they reached that count, so the top of the stack is the most recently pushed one among them.

Why is the same value stored on several levels?

Each copy remembers the moment the value reached that count. When the top copy is popped, the copy below is already in the right place for the lower count, so nothing has to move.

Can maxfreq drop by more than one after a pop?

No. A pop removes one copy, and the value it came from still has its copy on the level just below, so that level is not empty.