155. Min Stack Leetcode Solution

Min Stack Leetcode Problem :

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.

jump game leetcode

Min Stack Leetcode Solution :

Constraints :

  • -2^31 <= val <= 2^31 – 1
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • At most 3 * 104 calls will be made to push, pop, top, and getMin.

Intuition :

The MinStack class is designed to maintain a stack of elements while also keeping track of the minimum element in the stack.

Approach :

1. The MinStack class uses a single stack, stk, to store pairs of elements and the minimum values encountered so far.
2: When an element is pushed onto the stack, the current minimum value is calculated by comparing the new element with the minimum value stored on top of the stack. The pair (element, current minimum) is then pushed onto the stack.
3: When an element is popped from the stack, it effectively removes the top pair, effectively reverting to the previous state.
4: The top function returns the first element of the top pair on the stack, and the getMin function returns the second element of the top pair, which represents the current minimum value.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription