Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Implement Min Stack

Medium Acceptance 22.59% Points 30.00

You are tasked with implementing a stack that supports the following operations while handling up to q queries:

  1. Push: Add an integer x to the top of the stack.
  2. Pop: Remove and return the top element of the stack. If the stack is empty, return -1.
  3. GetMin: Retrieve the smallest element in the stack in constant time (O(1)). If the stack is empty, return -1.

You will receive a series of queries, and each query will perform one of the following actions:

  • 1 x: Add the integer x to the top of the stack.
  • 2: Remove and return the top element of the stack. If the stack is empty, return -1.
  • 3: Return the smallest element in the stack. If the stack is empty, return -1.
Examples
Example 1

Example 1

Input: q = 4, queries = [(1, 5), (1, 7), (3), (2)]

Output: 5, 7

Explanation: push(5): Add 5 to the stack. Stack becomes {5}. push(7): Add 7 to the stack. Stack becomes {5, 7}. getMin(): The smallest element in the stack is 5.

Output: 5. pop(): Remove and return the top element (7). Stack becomes {5}.

Output: 7.

Example 2

Example 2

Input: q = 5, queries = [(1, 10), (2), (3), (2), (3)]

Output: 10, -1, -1, -1

Explanation: push(10): Add 10 to the stack. Stack becomes {10}. pop(): Remove and return the top element (10). Stack becomes (empty).

Output: 10. getMin(): The stack is empty, so return -1.

Output: -1. pop(): The stack is empty, so return -1.

Output: -1. getMin(): The stack is empty, so return -1.

Output: -1.

Hints
Hint 1
Expected Time Complexity: O(1)
Hint 2
Expected Auxiliary Space: O(1)
Constraints
  • 1 <= q <= 100
  • 1 <= values on the stack <= 100
Companies
Amazon Microsoft Walmart Goldman Sachs Flipkart
Topics
Stack
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions