HardHash TableStackDesignOrdered Set

Maximum Frequency Stack

1 approach, code in every language

Problem description

Design a stack-like structure that always removes the most frequently pushed element.

Implement FreqStack with two operations: push(val) adds an integer to the structure, and pop() removes and returns the element that has been pushed most often. If several elements tie for the highest frequency, remove the one that was pushed most recently.

Example 1

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

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

After the pushes, counts are 5:3, 7:2, 4:1. pop() returns 5 (most frequent), then 7 (now 5 and 7 both have count 2, 7 was pushed more recently), then 5, then 4.

Example 2

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

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

Counts after pushes are 1:2, 2:1. pop() returns 1 (highest frequency); the next pop() sees 1 and 2 both at count 1, and 1 was pushed most recently, so it returns 1 again.

Constraints

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

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free