Python coding

Stack that pops the most frequent value

Write a class FrequencyStack of integers.

  • push(x) puts x on top of the stack.
  • pop() finds the value with the most copies in the stack, removes its copy nearest the top and returns it. If several values tie for the most copies, it picks the one whose highest copy is nearest the top.

Values may be negative. pop is never called on an empty stack. Both operations must be O(1) on average.

The tests call the provided run_stack(ops): it applies each operation in order and returns the list of results (None for push, shown as null).

Besides the tests, one large input (7,500 pushes, 2,500 pops) with a ~380 ms limit (scaled to your device's speed): brute force won't pass.

  • run_stack([["push",5],["push",7],["push",5],["push",7],["push",4],["push",5],["pop"],["pop"],["pop"],["pop"]]) → [null,null,null,null,null,null,5,7,5,4]
  • run_stack([["push",1],["push",2],["push",3],["pop"],["pop"],["push",2],["pop"]]) → [null,null,null,3,2,null,2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Counting copies is a hash map. The hard part is the tie rule: among the most frequent values, the most recently pushed wins, which smells like a stack.

Hint 2

When x gets its k-th copy, push x onto a separate stack for level k. Level k then holds, newest on top, every value that has reached k copies.

Hint 3

pop takes the top of the highest non-empty level. A value with k copies sits in levels 1 to k, so when the top level empties, the one below still holds something.

Solution and why it works
pythonO(1) average per operation · O(n)
# --- your code ---
from collections import Counter, defaultdict


class FrequencyStack:
    def __init__(self):
        self.count = Counter()               # value -> copies in the stack
        self.levels = defaultdict(list)      # k -> values in push order of their k-th copy
        self.top = 0                         # highest level that holds anything

    def push(self, x: int) -> None:
        self.count[x] += 1
        self.top = max(self.top, self.count[x])
        self.levels[self.count[x]].append(x)  # lower levels keep its earlier copies

    def pop(self) -> int:
        x = self.levels[self.top].pop()      # most frequent; the newest among ties
        self.count[x] -= 1
        if not self.levels[self.top]:
            self.top -= 1                    # x's earlier copy, if any, is one level down
        return x


# --- provided: do not edit ---
def run_stack(ops: list[list]) -> list:
    stack = FrequencyStack()
    return [getattr(stack, name)(*args) for name, *args in ops]

Split the stack by frequency: the k-th copy of a value goes onto the stack for level k, and a counter tracks copies. The highest non-empty level holds exactly the most frequent values, in the order they reached that count, so its top is the answer, tie rule included. Popping it leaves that value's lower copies in place; if the level empties, the one below is non-empty, so top steps down by one. Scanning the whole stack for the most frequent value costs O(n) per pop.