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^9At most 2 * 10^4 calls will be made to push and popIt is guaranteed that there is at least one element in the stack before each call to popSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI