Maximum Frequency Stack solution explained

Maximum Frequency Stack asks for a stack whose pop removes the value that currently appears most often, choosing the most recently pushed one on a tie. Keep a count per value and a separate stack for each frequency level: pushing a value whose count becomes f puts it on stack f, and popping takes the top of the highest non-empty level, then lowers that value's count. Both operations run in O(1) time, with O(n) memory for n pushed values.

By Published 7 min read

The problem, restated

Design a container with two operations. push(x) adds the integer x. pop() removes one copy of the value that occurs most often among the values currently stored and returns it. If several values share the highest count, remove the one whose latest copy was pushed most recently. You may assume pop is only called when the container is not empty.

An example sequence written for this page
OperationReturnsCounts afterward
push 4, push 7, push 4, push 2, push 7, push 44: 3, 7: 2, 2: 1
pop44: 2, 7: 2, 2: 1
pop74: 2, 7: 1, 2: 1 (7's second copy was pushed after 4's second copy)
pop44: 1, 7: 1, 2: 1
pop24: 1, 7: 1 (2 was the latest first-copy push)
pop74: 1
pop4empty
An example sequence written for this page. Scroll sideways on a small screen.

The second pop is the subtle one. Both 4 and 7 have count 2 at that moment. The tie goes to the value whose second copy arrived later, which is 7, pushed fifth, rather than 4, whose second copy was pushed third. A design that stores one "last pushed" time per value and never rolls it back on pop would still credit 4 with the sixth push, which has already been popped, and pick 4 wrongly.

What the interviewer is testing

This is a design question that rewards finding the right grouping. Interviewers watch for candidates who first propose a heap, which is correct but heavier than needed, and then see that frequencies only change by one at a time. That observation leads to the stack-per-level design with constant-time operations. Clear handling of the tie rule, and a crisp reason why max_freq only ever drops by one, are what separate strong answers.

Follow-ups

  • Add peek(). Return the top of stack max_freq without removing it.
  • Pop the least frequent instead. Harder, because the minimum level can jump when values disappear; a heap or ordered map is simpler there.
  • Remove a specific value. Needs a way to find its copies inside level stacks, such as linked nodes with a per-value index.
  • Thread safety. One lock around both operations is enough, since each touches a few entries.

Brute force

Store every pushed value in a list. On pop, count every value, find the highest count, then scan from the end of the list for the first value with that count and remove that position. Scanning from the end gives the right tie-break: the first match from the end is the value with the highest count whose latest copy is most recent. Each pop costs O(n).

from collections import Counter

class FreqStackSlow:
    def __init__(self):
        self.items = []

    def push(self, x):
        self.items.append(x)

    def pop(self):
        counts = Counter(self.items)
        top = max(counts.values())
        for i in range(len(self.items) - 1, -1, -1):
            if counts[self.items[i]] == top:
                return self.items.pop(i)
Python: list plus a scan on every pop.

One stack per frequency level

Think of each push as giving a value a new level. The first copy of 4 goes on level 1, the second on level 2, the third on level 3. Every level is a plain stack in push order. The most frequent value is on the highest non-empty level, and among values on that level the top of its stack is the one that reached that level most recently, which is exactly the tie rule.

Levels after the six pushes in the example
LevelStack (bottom to top)
3[4]
2[4, 7]
1[4, 7, 2]
Levels after the six pushes in the example. Scroll sideways on a small screen.

Popping takes 4 from level 3, which empties it, so max_freq becomes 2. Next pop takes 7 from level 2, then 4. Then level 1 gives 2, 7 and 4. Notice that popping never needs to look below the top level: lowering a value's count does not move its other copies, because they already sit on the lower levels where they belong.

Why does max_freq drop by exactly one when its stack empties? The value just popped had count max_freq and now has max_freq - 1, and its copy at that level is still there. So level max_freq - 1 is never empty at that moment.

from collections import defaultdict

class FreqStack:
    def __init__(self):
        self.count = defaultdict(int)
        self.levels = defaultdict(list)
        self.max_freq = 0

    def push(self, x):
        self.count[x] += 1
        f = self.count[x]
        self.levels[f].append(x)
        self.max_freq = max(self.max_freq, f)

    def pop(self):
        x = self.levels[self.max_freq].pop()
        self.count[x] -= 1
        if not self.levels[self.max_freq]:
            del self.levels[self.max_freq]
            self.max_freq -= 1
        return x
Python: counts, level stacks and the current maximum level.
class FreqStackJs {
  constructor() {
    this.count = new Map();
    this.levels = new Map();
    this.maxFreq = 0;
  }

  push(x) {
    const f = (this.count.get(x) || 0) + 1;
    this.count.set(x, f);
    if (!this.levels.has(f)) this.levels.set(f, []);
    this.levels.get(f).push(x);
    this.maxFreq = Math.max(this.maxFreq, f);
  }

  pop() {
    const level = this.levels.get(this.maxFreq);
    const x = level.pop();
    this.count.set(x, this.count.get(x) - 1);
    if (level.length === 0) {
      this.levels.delete(this.maxFreq);
      this.maxFreq -= 1;
    }
    return x;
  }
}
JavaScript: the same design with Maps.

Heap alternative

Give every push a timestamp. Store (count after this push, timestamp, value) in a max-heap; pop the largest and decrement the value's count. The count stored in each entry is the count at the time of that push, which matches the level idea, so stale entries never appear. This is O(log n) per operation and is a reasonable first answer before you simplify.

import heapq
from collections import defaultdict

class FreqStackHeap:
    def __init__(self):
        self.count = defaultdict(int)
        self.heap = []
        self.time = 0

    def push(self, x):
        self.count[x] += 1
        self.time += 1
        heapq.heappush(self.heap, (-self.count[x], -self.time, x))

    def pop(self):
        _, _, x = heapq.heappop(self.heap)
        self.count[x] -= 1
        return x
Python: heap of (-count, -time, value).

Complexity

n values currently stored
DesignpushpopMemory
List with a scanO(1)O(n)O(n)
Heap with timestampsO(log n)O(log n)O(n)
Stack per frequency levelO(1)O(1)O(n)
n values currently stored. Scroll sideways on a small screen.

Memory for the level design is O(n) because every stored copy appears in exactly one level stack, plus one count entry per distinct value.

Edge cases

  • All pushes of the same value: it behaves like an ordinary stack of that value.
  • All values distinct: every pop returns the latest push, like an ordinary stack.
  • Pushes after pops, which must reuse levels that were emptied and deleted.
  • Ties at the top level between a value pushed early and one pushed late, as in the second pop above.
  • Negative numbers or zero, which are fine as map keys.

Common mistakes

  • Keeping one last-push time per value that goes stale after a pop, instead of letting each level's stack remember when the value reached that count.
  • Moving a value's copies between levels when its count changes; they never need to move.
  • Searching for the next non-empty level with a loop, when it is always max_freq - 1.
  • Forgetting to decrement the count on pop, so the next push of that value lands on the wrong level.
  • Storing only counts and a global order, then trying to recover the tie-break with sorting on every pop.

How to explain it out loud

Fictional example

From a heap to levels
Candidate
A heap ordered by count and then push time works in log time. But counts only change by one, which suggests grouping by count instead.
Candidate
When a value's count becomes f, I push it onto stack f. A value with three copies sits on stacks 1, 2 and 3. Pop takes the top of the highest stack, which is the most frequent value and, among ties, the one that reached that count most recently.
Candidate
After a pop, the popped value still has a copy one level down, so if the top stack empties, the new maximum is exactly one lower. Both operations are constant time.

LRU Cache is another design question where the trick is choosing structures so every operation is O(1). Top K Frequent Words and Reorganize String also turn counts into an order, each with its own tie rule. Valid Parentheses is the simplest stack problem, a good warm-up for the level idea.

Practicing with Natively

Design questions are mostly about explaining your structure, so practice drawing the levels while you talk. In a practice session on Mac or Windows, Natively can read the prompt from a screenshot and suggest a design to compare with yours after your own attempt, and the transcript of the mock round shows whether the tie rule came across clearly. Read about the AI interview assistant.

Questions people ask

How do you implement a maximum frequency stack?

Keep a count per value and a stack per frequency. On push, increment the count to f and push onto stack f. On pop, take the top of the highest non-empty stack and decrement that value's count.

How are ties handled in Maximum Frequency Stack?

Among values with the highest count, the one that reached that count most recently is on top of that level's stack, so it is popped first.

Why does max_freq only drop by one?

The popped value keeps a copy on the level below, so that level cannot be empty when the top level empties.

What is the time complexity?

O(1) for push and pop with level stacks, O(log n) with a heap of (count, push time), and O(n) per pop for a list scan.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP