Min Stack (155)
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Approach:
Create a private inner class for the nodes in order to form the LinkedList.
When pushing into the stack, add element to the head of LinkedList to simulate the LIFO property.
To avert conducting a linear search when
getMin()
function is called, insert amin
data field to Node class which will inform us of the min at each desired point consequently allowing retrieval inO(1).
Since we always have a pointer to the head, when we pop, we simply move the pointer to the next Node.
Time complexity: O(1) Space Complexity: O(N)
Last updated
Was this helpful?