Maximum Frequency Stack

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

Design a stack that always pops the most frequently occurring element. If there is a tie, pop the most recently pushed element among the most frequent.

Implement a function that processes an array of operations and an array of arguments:

  • "FreqStack" — Initializes the frequency stack.
  • "push" — Pushes val onto the stack.
  • "pop" — Removes and returns the most frequent element. If there is a tie in frequency, the most recently pushed element is returned.

Examples

Example 1:

Input: operations = ["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"], args = [[],[5],[7],[5],[7],[4],[5],[],[],[],[]]

Output: [null,null,null,null,null,null,null,5,7,5,4]

Explanation: Push 5,7,5,7,4,5. Frequencies: 5→3, 7→2, 4→1. Pop: 5 (most frequent, freq=3). Pop: 7 (tie at freq=2 between 5 and 7; 7 was pushed last). Pop: 5 (freq=2). Pop: 4 (only freq=1 element remaining is 4 or 7; 4 was pushed more recently at that level).

Example 2:

Input: operations = ["FreqStack","push","push","push","pop","pop","pop"], args = [[],[1],[1],[2],[],[],[]]

Output: [null,null,null,null,1,1,2]

Explanation: Push 1,1,2. Frequencies: 1→2, 2→1. Pop: 1 (freq=2). Pop: 1 (freq=1 now, but 1 still in stack). Pop: 2.

Constraints

  • 0 <= val <= 10^9
  • At most 2 * 10^4 calls to push and pop
  • pop is never called on an empty stack
Source: Custom Data Structures pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle