AlgoLounge

Maximum Frequency Stack

hard

Design a stack-like data structure that pops the most frequent element.

Implement the FreqStack class:

  • FreqStack(): Constructs an empty frequency stack
  • push(val): Pushes an integer val onto the top of the stack
  • 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

Examples

Example 1

Input:  

["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output: [null, null, null, null, null, null, null, 5, 7, 5, 4] FreqStack freqStack = new FreqStack(); freqStack.push(5); // stack: [5] freqStack.push(7); // stack: [5,7] freqStack.push(5); // stack: [5,7,5] freqStack.push(7); // stack: [5,7,5,7] freqStack.push(4); // stack: [5,7,5,7,4] freqStack.push(5); // stack: [5,7,5,7,4,5] freqStack.pop(); // return 5 (freq=3), stack: [5,7,5,7,4] freqStack.pop(); // return 7 (freq=2), stack: [5,7,5,4] freqStack.pop(); // return 5 (freq=2), stack: [5,7,4] freqStack.pop(); // return 4 (freq=1), stack: [5,7]

Constraints

  • 0 <= val <= 10^9
  • At most 2 * 10^4 calls will be made to push and pop
  • It is guaranteed that there will be at least one element in the stack before calling pop

How the tests work: each test is a sequence of calls. operations[i] is the method called with arguments[i]; the first entry constructs the class. The expected output lists what every call returns — null for the constructor and for methods that return nothing.

TypeScript
Loading editor…
List of test cases (10)
Case 1
operations = ["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"]
arguments = [[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
Case 2
operations = ["FreqStack","push","push","pop","pop"]
arguments = [[],[1],[1],[],[]]
Case 3
operations = ["FreqStack","push","push","push","pop"]
arguments = [[],[1],[2],[3],[]]
Case 4
operations = ["FreqStack","push","push","push","push","pop","pop"]
arguments = [[],[4],[4],[4],[4],[],[]]
Case 5
operations = ["FreqStack","push","push","push","push","push","pop","push","pop","pop"]
arguments = [[],[1],[2],[1],[2],[1],[],[3],[],[]]
Case 6
operations = ["FreqStack","push","push","push","push","push","push","pop","pop","pop"]
arguments = [[],[9],[8],[9],[8],[9],[8],[],[],[]]
Case 7
operations = ["FreqStack","push","pop"]
arguments = [[],[5],[]]
Case 8
operations = ["FreqStack","push","push","push","pop","pop","pop"]
arguments = [[],[1],[2],[3],[],[],[]]
Case 9
operations = ["FreqStack","push","push","push","push","push","pop","pop","pop","pop","pop"]
arguments = [[],[10],[20],[10],[30],[10],[],[],[],[],[]]
Case 10
operations = ["FreqStack","push","push","push","push","push","push","pop","pop","push","pop","pop"]
arguments = [[],[7],[7],[3],[7],[3],[3],[],[],[7],[],[]]