895. Maximum Frequency Stack

Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.

Implement the FreqStack class:

  • FreqStack() constructs an empty frequency stack.
  • void push(int val) pushes an integer val onto the top of the stack.
  • int pop() removes and returns the most frequent element in the stack.
    • If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.

Dictionary of List

class FreqStack(object): 
    def __init__(self): 
        self.freq = collections.Counter() 
        self.group = collections.defaultdict(list) 
        self.maxfreq = 0

    def push(self, x): 
        f = self.freq[x] + 1 
        self.freq[x] = f 
        if f > self.maxfreq: 
            self.maxfreq = f 
        self.group[f].append(x)

    def pop(self): 
        x = self.group[self.maxfreq].pop() 
        self.freq[x] -= 1 
        if not self.group[self.maxfreq]: 
            self.maxfreq -= 1 
        return x

Use a timer

class FreqStack: 
    def __init__(self): 
        self.h = [] 
        self.timer = 0 
        self.freq = collections.defaultdict(int) 

    def push(self, val: int) -> None: 
        self.freq[val] += 1 
        heappush(self.h, (-self.freq[val], -self.timer, val)) 
        self.timer += 1 
        
    def pop(self) -> int: 
        _, _, val = heappop(self.h) 
        self.freq[val] -= 1 
        return val