HardNeetCode150Hash TableStackDesignHeap (Priority Queue)

Maximum Frequency Stack

Design stack that pops most frequent element.

Examples

Input
FreqStack: push(5),push(7),push(5),push(7),push(4),pop,pop,pop,pop
Output
5,7,5,4

Pop most frequent, ties use most recent.

Constraints

  • 1 <= val <= 10^4
  • 1 <= operation <= 10^4
  • All valid operations

Approaches

Track freq, sort on pop.

CodeT: O(n log n) pop | S: O(n) storage

Bucket by frequency.

CodeT: O(1) push/pop | S: O(n) storage

Same approach.

CodeT: O(1) push/pop | S: O(n)

Complexity Comparison

HashMap + Sort
T: O(n log n) popS: O(n) storage

Track freq, sort on pop.

HashMap + Bucket
T: O(1) push/popS: O(n) storage

Bucket by frequency.

HashMap + Frequency Buckets
T: O(1) push/popS: O(n)

Same approach.

Common Mistakes

Not handling ties correctly

Wrong frequency update

Off-by-one in bucket

Try It Yourself

Copy the optimal solution and run it in our compiler.

Open in Compiler