WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Stack and Queue Problems · question 51 of 120

Can you design a stack with a function that returns the minimum element in constant time?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics