πDay 7. 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.
π Example Walkthrough:
Example 1
Input:
q = 7
queries = [[1, 2], [1, 3], [3], [2], [4], [1, 1], [4]]Output:
[3, 2, 1]Explanation:
Example 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)
π Solution Code
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