#895

Maximum Frequency Stack

Hard
Hash TableStackDesignOrdered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we use a combination of a frequency map and a stack of stacks. Each frequency level has its own stack, allowing us to efficiently manage and pop the most frequent elements.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a frequency map to count occurrences of each element.
  2. 2Step 2: Use a map of stacks to store elements by their frequency.
  3. 3Step 3: For each push, increment the frequency and push the element onto the corresponding stack.
  4. 4Step 4: For each pop, retrieve the stack of the highest frequency and pop the top element.
solution.py22 lines
1# Full working Python code
2class FreqStack:
3    def __init__(self):
4        self.freq = {}
5        self.freq_stack = {}
6        self.max_freq = 0
7
8    def push(self, val: int) -> None:
9        self.freq[val] = self.freq.get(val, 0) + 1
10        f = self.freq[val]
11        if f > self.max_freq:
12            self.max_freq = f
13        if f not in self.freq_stack:
14            self.freq_stack[f] = []
15        self.freq_stack[f].append(val)
16
17    def pop(self) -> int:
18        val = self.freq_stack[self.max_freq].pop()
19        self.freq[val] -= 1
20        if not self.freq_stack[self.max_freq]:
21            self.max_freq -= 1
22        return val

Complexity note: The time complexity is O(n) for push and pop operations because we are using a hashmap and stacks to manage frequencies and elements efficiently, allowing us to access and modify them in constant time.

  • 1Using a frequency map allows efficient tracking of element counts.
  • 2Stack of stacks enables O(1) access to the most frequent elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.