KatInterview

931. Maximum Frequency Stack

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a FreqStack, a data structure that behaves like a stack but with a special pop operation. The pop method must remove and return the element with the highest frequency. If there's a tie in frequency, it should remove the one that was pushed most recently (i.e., the one closest to the top of a regular stack).

Solution

Maximum Frequency Stack in Python

import collections

class FreqStack:

    def __init__(self):
        # Dictionary to store frequency of each element
        self.freq = collections.defaultdict(int)
        # Dictionary to store lists (acting as stacks) of elements for each frequency
        self.group = collections.defaultdict(list)
        # Variable to keep track of the maximum frequency
        self.max_freq = 0

    def push(self, val: int) -> None:
        # Increment frequency of the element
        self.freq[val] += 1
        f = self.freq[val]
        
        # Update max_freq if necessary
        if f > self.max_freq:
            self.max_freq = f
        
        # Append the element to the list corresponding to its new frequency.
        # This list acts as a stack.
        self.group[f].append(val)

    def pop(self) -> int:
        # Get the list of elements with the highest frequency
        top_list = self.group[self.max_freq]
        
        # Pop the last element. This is the most recent element with max frequency.
        val = top_list.pop()
        
        # Decrement its frequency
        self.freq[val] -= 1
        
        # If the list for max_freq is now empty, it means we no longer have elements
        # with that frequency, so we decrement max_freq.
        if not top_list:
            self.max_freq -= 1
            
        return val


# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(val)
# param_2 = obj.pop()

Maximum Frequency Stack in Java

class FreqStack {
    // Map to store frequency of each element
    private Map<Integer, Integer> freqMap;
    // Map to store stacks of elements for each frequency
    private Map<Integer, Stack<Integer>> groupMap;
    // Variable to keep track of the maximum frequency
    private int maxFreq;

    public FreqStack() {
        freqMap = new HashMap<>();
        groupMap = new HashMap<>();
        maxFreq = 0;
    }
    
    public void push(int val) {
        // Get current frequency of val, or 0 if it's not present.
        // Then increment it for the new frequency.
        int f = freqMap.getOrDefault(val, 0) + 1;
        freqMap.put(val, f);
        
        // Update maxFreq if this element's frequency is now the highest.
        if (f > maxFreq) {
            maxFreq = f;
        }
        
        // Get the stack for this frequency f. If it doesn't exist, create it.
        // Then push the element onto this stack.
        groupMap.computeIfAbsent(f, k -> new Stack<>()).push(val);
    }
    
    public int pop() {
        // Get the stack of elements with the highest frequency.
        Stack<Integer> topStack = groupMap.get(maxFreq);
        // Pop the element. Due to stack's LIFO property, this is the most recently
        // pushed element among those with the maximum frequency.
        int val = topStack.pop();
        
        // Decrement the frequency of the popped element.
        freqMap.put(val, freqMap.get(val) - 1);
        
        // If the stack for the current maxFreq is now empty, it means we have no more
        // elements with that frequency. So, the new max frequency is one less.
        // The problem guarantees pop is only called on non-empty stacks, so we don't
        // need to worry about maxFreq becoming 0 when it shouldn't.
        if (topStack.isEmpty()) {
            maxFreq--;
        }
        
        return val;
    }
}

/**
 * Your FreqStack object will be instantiated and called as such:
 * FreqStack obj = new FreqStack();
 * obj.push(val);
 * int param_2 = obj.pop();
 */

Maximum Frequency Stack in C++

class FreqStack {
private:
    // Map to store frequency of each element
    std::unordered_map<int, int> freqMap;
    // Map to store stacks of elements for each frequency
    std::unordered_map<int, std::stack<int>> groupMap;
    // Variable to keep track of the maximum frequency
    int maxFreq;

public:
    FreqStack() {
        maxFreq = 0;
    }
    
    void push(int val) {
        // Increment frequency of val
        freqMap[val]++;
        int f = freqMap[val];
        
        // Update maxFreq if necessary
        if (f > maxFreq) {
            maxFreq = f;
        }
        
        // Push the element to the stack corresponding to its new frequency
        groupMap[f].push(val);
    }
    
    int pop() {
        // Get the stack for the max frequency
        std::stack<int>& topStack = groupMap[maxFreq];
        
        // Get the element to pop (most frequent, and most recent among ties)
        int val = topStack.top();
        topStack.pop();
        
        // Decrement its frequency
        freqMap[val]--;
        
        // If the stack for maxFreq is now empty, it means we no longer have elements
        // with that frequency, so we decrement maxFreq.
        if (topStack.empty()) {
            maxFreq--;
        }
        
        return val;
    }
};

/**
 * Your FreqStack object will be instantiated and called as such:
 * FreqStack* obj = new FreqStack();
 * obj->push(val);
 * int param_2 = obj->pop();
 */

Maximum Frequency Stack in TypeScript

class FreqStack {
    // Map to store frequency of each element
    private freqMap: Map<number, number>;
    // Map to store arrays (acting as stacks) of elements for each frequency
    private groupMap: Map<number, number[]>;
    // Variable to keep track of the maximum frequency
    private maxFreq: number;

    constructor() {
        this.freqMap = new Map();
        this.groupMap = new Map();
        this.maxFreq = 0;
    }

    push(val: number): void {
        // Get current frequency of val, or 0 if it's not present.
        // Then increment it for the new frequency.
        let f = (this.freqMap.get(val) || 0) + 1;
        this.freqMap.set(val, f);

        // Update maxFreq if this element's frequency is now the highest.
        if (f > this.maxFreq) {
            this.maxFreq = f;
        }

        // Get the stack (array) for this frequency f. If it doesn't exist, create it.
        if (!this.groupMap.has(f)) {
            this.groupMap.set(f, []);
        }
        // Push the element onto this stack.
        this.groupMap.get(f)!.push(val);
    }

    pop(): number {
        // Get the stack of elements with the highest frequency.
        let topStack = this.groupMap.get(this.maxFreq)!;
        // Pop the element. This is the most recently pushed element among those with the maximum frequency.
        let val = topStack.pop()!;

        // Decrement the frequency of the popped element.
        this.freqMap.set(val, this.freqMap.get(val)! - 1);

        // If the stack for the current maxFreq is now empty, it means we have no more
        // elements with that frequency. So, the new max frequency is one less.
        if (topStack.length === 0) {
            this.maxFreq--;
        }

        return val;
    }
}

/**
 * Your FreqStack object will be instantiated and called as such:
 * var obj = new FreqStack()
 * obj.push(val)
 * var param_2 = obj.pop()
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.