Stack That Can Also Remove Its Largest Element
Last updated: November 29, 2026
Quick Overview
Implement a stack supporting push, pop, top, peek_max and pop_max, where pop_max removes the most recently pushed copy of the largest value. Aim for O(log n) per operation.
Meta
November 29, 20260
0
0 solved
Implement a stack supporting push, pop, top, peek_max and pop_max, where pop_max removes the most recently pushed copy of the largest value. Aim for O(log n) per operation.
A Meta onsite favorite because it forces two views of the same data to stay consistent. The interviewer checks that you avoid the O(n) approach, choose lazy deletion or a balanced structure, and resolve ties toward the top of the stack.
What the Interviewer Expects
- Explain why a simple max-tracking stack fails for pop_max
- Pair a stack with a heap keyed by value and recency
- Use unique ids and lazy deletion to keep both in sync
- Break ties so the most recent maximum is removed
- State amortized complexity precisely
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Can you get O(1) pop and top while keeping O(log n) pop_max?
- How would you implement this with a sorted map and doubly linked list instead?
- How does memory behave if many items are lazily deleted but not yet cleaned?
- What changes if you need pop_min as well?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
push(v),pop(),top(),peek_max(),pop_max().- Ties on max: remove the copy closest to the top.
- Operations are valid only on a non-empty stack....
High-Level Design
Give each push a unique increasing id. The stack holds (id, value); a max-heap holds (-value, -id), so ties favor larger ids (more recent). When one side removes an element, record its id in a `re...