Skip to content

Practice Maximum Frequency Stack

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#895
LeetCode Problem

Maximum Frequency Stack

Problem Statement

FreqStack.push(val) records a value. pop() removes and returns a value with the highest current frequency; among ties, remove the occurrence closest to the stack top. pop is called only when nonempty. Practice approach: Track each value's frequency and a stack of values for each attained frequency. Push onto the new-frequency stack; pop from the maximum-frequency stack and reduce that value's count. When the group empties, reduce the maximum frequency. This preserves recency within ties in O(1) time per operation.

Source: Maximum Frequency Stack on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["FreqStack","push","push","push","push","pop","pop","pop"]
[[],[4],[7],[4],[7],[],[],[]]
Output
[null,null,null,null,null,7,4,7]
Explanation

At frequency two, 7 is more recent. After removing 7 then 4, both remaining values tie and 7 is again more recent.

Constraints

0 <= val <= 10^9
At most 2 * 10^4 total calls.
The stack is nonempty before pop.

Related LeetCode Problems

Practice more problems similar to Maximum Frequency Stack.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.