Maximum Frequency Stack
Design a stack-like structure FreqStack. push(val) adds a value. pop() removes and returns the most frequent value; if several values tie for most frequent, return the one that was pushed most recently.
Open official problem prompt ↗Always return the element with the highest current occurrence count, breaking ties in favor of the most recently pushed value.
Imagine stacking poker chips into columns by how many times a color has appeared: the first red chip goes in column 1, the second red in column 2, and so on. To pop, you grab the top chip of the tallest column.
- Input
- FreqStack(); push(5); push(7); push(5); push(7); push(4); push(5); pop(); pop(); pop(); pop()
- Output
- [null, null, null, null, null, null, null, 5, 7, 5, 4]
- Why
- Counts are 5:3, 7:2, 4:1. pop returns 5 (freq 3); then 7 and 5 tie at freq 2 so the more recent 7 wins, then 5; then 4 at freq 1.
0 <= val <= 10^9At most 2 * 10^4 calls to push and pop combinedIt is guaranteed pop is only called on a non-empty stack