We can design such a stack using an additional data structure to keep track of the minimum element. We could use an auxiliary stack to just keep track of the minimum element.
The standard operations on a stack are:
1. ‘push()‘ - Adds an element to the top of the stack.
2. ‘pop()‘ – Removes an element from the top of the stack.
3. ‘top()‘ or ‘peek()‘ - Returns the top element of the stack.
4. ‘is_empty()‘ - Checks if the stack is empty.
5. ‘size()‘ – Returns the size of the stack.
But, to this, we are adding another operation ‘get_min()‘ that retrieves the minimum element from the stack in constant time ‘O(1)‘.
For simplicity, let’s say the stack holds integers.
A stack can be implemented using a LinkedList or an Array or a Dynamic Array. Here we will discuss the algorithm which uses two stacks:
We utilize two stacks, ‘mainStack‘ and ‘minsStack‘. The ‘mainStack‘ holds the actual elements in the stack, while the ‘minsStack‘ holds the minimum elements. The top of ‘minsStack‘ always shows the minimum element from ‘mainStack‘.
Here is the Python algorithm to implement this:
class MinStack:
def __init__(self):
self.mainStack = []
self.minsStack = []
# Push operation for adding elements to stack
def push(self, value):
self.mainStack.append(value)
if len(self.minsStack) == 0 or value <= self.minsStack[-1]:
self.minsStack.append(value)
# Pop operation for removing elements from stack
def pop(self):
if len(self.mainStack) == 0:
return None
removed_element = self.mainStack.pop()
if removed_element == self.minsStack[-1]:
self.minsStack.pop()
return removed_element
# Get Min operation to retrieve minimum element from stack
def get_min(self):
if len(self.minsStack) == 0:
return None
return self.minsStack[-1]
This algorithm ensures all operations (‘push()‘, ‘pop()‘, and ‘get_min()‘) are done in constant time(‘O(1)‘), and it uses ‘O(n)‘ additional space.
Please remember that ‘get_min()‘ does not remove the minimum element – it just returns it.
Regarding mathematical formulas, there is not a lot except for algorithmic time complexity. The crucial part is understanding how two stacks work together to maintain min value, which allows ‘get_min()‘ to always have an ‘O(1)‘ time complexity.