27. Get Min from Stack
The problem can be found at the following link: Question Link
Problem Description
Implement a stack that supports the following operations in O(1) time:
push(x): Push an integer x onto the stack.pop(): Remove the top element from the stack.peek(): Return the top element of the stack. If empty, return-1.getMin(): Retrieve the minimum element in the stack. If empty, return-1.
Examples
Example 1
Input:
q = 7
queries = [[1, 2], [1, 3], [3], [2], [4], [1, 1], [4]]Output:
[3, 2, 1]Explanation:
push(2) -> Stack: [2]
push(3) -> Stack: [2, 3]
peek() -> 3
pop() -> Stack: [2]
getMin() -> 2
push(1) -> Stack: [2, 1]
getMin() -> 1Example 2
Input:
Output:
Explanation:
Constraints
$(1 \leq q \leq 10^5)$ (Number of queries)
$(1 \leq x \leq 10^9)$ (Stack elements are within this range)
My Approach
Using Two Stacks (O(1) Time, O(N) Space)
Use two stacks:
sβ Normal stack for elements.minStackβ Keeps track of minimum values.
When pushing an element
x, check:If
minStackis empty orx <= minStack.top(), pushxintominStack.
While popping, if the popped element is the current min, pop from
minStack.getMin()always returnsminStack.top().
Time and Auxiliary Space Complexity
Operation
Time Complexity
Space Complexity
push(x)
O(1)
O(N) (extra stack)
pop()
O(1)
O(N) (extra stack)
peek()
O(1)
O(1)
getMin()
O(1)
O(1)
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated