Implement a Min Stack

Data Structures
Medium
Apple
101.4K views

Design a stack that supports push, pop, top, and retrieving the minimum element in $O(1)$ time. This requires using auxiliary storage with the main stack.

Why Interviewers Ask This

Apple interviewers prioritize engineers who optimize for both time and space efficiency while maintaining code clarity. This question evaluates your ability to balance O(1) retrieval constraints with auxiliary storage trade-offs. It specifically tests your understanding of stack mechanics, edge case handling like duplicate minimums, and your capacity to design robust data structures under strict performance requirements.

How to Answer This Question

1. Clarify Requirements: Immediately confirm that all operations including min retrieval must run in constant time and discuss the memory trade-off. 2. Propose a Two-Stack Strategy: Suggest using one stack for actual values and a second auxiliary stack to track the running minimum at each state. 3. Detail Push Logic: Explain that when pushing a new value, you compare it with the current top of the min-stack; push the smaller of the two or the value itself if the min-stack is empty. 4. Define Pop and Top: Describe how popping removes from both stacks simultaneously to maintain synchronization, ensuring the min-stack always reflects the correct minimum. 5. Analyze Complexity: Conclude by explicitly stating the O(1) time complexity for all operations and O(n) space complexity, demonstrating awareness of resource usage which aligns with Apple's focus on efficient system design.

Key Points to Cover

  • Explicitly defining the O(1) time constraint for all four operations
  • Correctly handling duplicate minimum values during push operations
  • Ensuring the auxiliary stack remains synchronized with the main stack during pop
  • Articulating the space-time trade-off clearly
  • Demonstrating clean, readable code structure suitable for production environments

Sample Answer

To implement a Min Stack with O(1) access to the minimum element, I would utilize a dual-stack approach. We need one primary stack to store all incoming elements and a secondary auxiliary stack dedicated solely to tracki…

Common Mistakes to Avoid

  • Attempting to scan the entire stack to find the minimum, resulting in O(n) time complexity
  • Failing to handle the scenario where multiple identical minimum values exist in the stack
  • Popping from the auxiliary stack even when the popped value is not the current minimum
  • Overlooking edge cases such as pushing to an empty stack or popping from an empty stack

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 166 Data Structures questionsBrowse all 54 Apple questions