Taro Logo

Min Stack

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+22
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1K views
Topics:
Stacks

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.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

Constraints:

  • -231 <= val <= 231 - 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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected data type and range of the values being pushed onto the stack (e.g., standard 32-bit integers, negative numbers, or floats)?
  2. What should `pop`, `top`, or `getMin` return if these operations are called on an empty stack?
  3. How should the stack handle duplicate minimum values (e.g., if we push two `3`s and then the first one is popped, should the minimum remain `3` until the second one is also removed)?
  4. Are there any memory limits or constraints on the number of elements the stack might hold during its lifecycle?
  5. Should we expect operations to be called in any particular sequence, or can `pop`, `top`, and `getMin` be invoked arbitrarily even when invalid?

Brute Force Solution

Approach

Imagine you have a stack of items where you can add, remove, and look at the top item whenever you want, but you also need to instantly know the smallest item currently in the stack. The brute force approach involves searching through the entire collection of items from scratch every single time someone asks for the smallest one.

Here's how the algorithm would work step-by-step:

  1. Whenever a new item is added to the stack, just place it on top of the existing items without doing any extra work.
  2. Whenever an item is removed from the stack, simply take off the top item.
  3. Whenever someone asks to see the top item, just point to the item currently sitting at the very top.
  4. Whenever someone asks for the smallest item currently in the stack, start at the top and look through every single item stored in the stack one by one.
  5. Compare all of them to find the absolute lowest value among the currently stored items.
  6. Return that lowest value as the answer to the request.

Code Implementation

class MinStack:
    def __init__(self):
        self.storage_stack = []

    def push(self, number_value):
        self.storage_stack.append(number_value)

    def pop(self):
        self.storage_stack.pop()

    def top(self):
        return self.storage_stack[-1]

    def getMin(self):
        # Scan all elements since we need the minimum without a tracking data structure
        current_minimum = self.storage_stack[0]

        for stack_item in self.storage_stack:
            # Compare each item to find the absolute lowest value currently stored
            if stack_item < current_minimum:
                current_minimum = stack_item

        return current_minimum

Big(O) Analysis

Time Complexity
O(n) – For standard operations like push, pop, and top, accessing the end of the stack takes constant time. However, the getMin operation requires searching through the entire collection of stored items one by one. If there are n elements currently in the stack, finding the smallest value forces us to inspect all n items individually. This linear scan results in a worst-case time complexity of O(n) for the minimum retrieval operation.
Space Complexity
O(N) – To satisfy the requirement of instantly knowing the smallest item in the stack, the algorithm maintains an auxiliary min stack alongside the main stack. As N elements are pushed onto the stack, both the main data structure and the minimum-tracking structure store up to N elements each. Because these extra structures scale directly in proportion to the number of stored items, the auxiliary space grows linearly with the input size N. Therefore, the total extra memory simplifies to Big O of N.

Optimal Solution

Approach

The optimal strategy involves using a companion tracker that remembers the smallest item seen so far at every single level of our main storage pile. By pairing each new item with the current minimum at the moment it arrives, we can instantly know the smallest item without ever having to search through the pile.

Here's how the algorithm would work step-by-step:

  1. Imagine building a tower of items where you can only add or remove from the very top.
  2. Whenever you place a new item onto the tower, check it against the smallest item that was already at the bottom.
  3. Keep a running note of what the smallest item is right now, and attach that information to the new item.
  4. If you remove the top item from the tower, the previous minimum automatically reappears because it was safely remembered right underneath.
  5. Whenever someone asks for the smallest item currently in the tower, just look at the note attached to whatever is sitting at the very top.
  6. Because every item carries its own historical record of the minimum at that exact moment, finding the smallest item takes zero extra search time.

Code Implementation

class MinStack:
    def __init__(self):
        self.storage_pile = []

    def push(self, new_item):
        # Pair the new item with the current minimum to remember historical minimums at every level.
        current_minimum = min(new_item, self.storage_pile[-1][1]) if self.storage_pile else new_item

        self.storage_pile.append((new_item, current_minimum))

    def pop(self):
        # Removing the top element automatically restores the previous minimum safely kept underneath.
        self.storage_pile.pop()

    def top(self):
        return self.storage_pile[-1][0]

    def get_min(self):
        # Looking at the attached note on the top item yields the minimum in constant time.
        return self.storage_pile[-1][1]

Big(O) Analysis

Time Complexity
O(1) – For each of the standard stack operations including push, pop, top, and retrieving the minimum, we only ever interact with the single item sitting at the very top of our tower. Because every pushed item carries its own pre-calculated minimum note from the moment of arrival, no searching or traversal is required. Whether we perform an operation once or n times, the time cost per operation remains constant. This constant-time execution across all methods simplifies to a total operational complexity of O(1).
Space Complexity
O(N) – The auxiliary space is driven by the internal data structure used to build the tower of items, where each pushed element is paired with its historical minimum. As N elements are added via push operations, the stack stores N pairs of values. Therefore, the extra memory required scales linearly with the number of elements N stored in the stack.

Edge Cases

Stack operations performed on an empty stack
How to Handle:
Methods like pop, top, and getMin should not be called on an empty stack according to problem constraints, but guard clauses can prevent underflow errors.
Stack containing only a single element
How to Handle:
The single element automatically becomes both the top and the minimum value.
Pushing multiple identical minimum values consecutively
How to Handle:
The minimum tracking structure must record duplicates so that popping one still leaves the correct minimum active.
Pushing strictly decreasing or strictly increasing sequences
How to Handle:
An auxiliary stack approach must push a new minimum on every decrease and ignore non-minimums to maintain constant time.
Handling extreme integer values such as Integer.MIN_VALUE and Integer.MAX_VALUE
How to Handle:
Standard integer types handle these bounds natively without causing overflow issues during simple comparisons.
Handling a large number of push operations reaching scale limits
How to Handle:
Dynamic array or linked list backing stores grow efficiently to accommodate extensive operations without manual resizing bugs.
Mixed sequence of pushes and pops with alternating minimums
How to Handle:
The secondary minimum stack pops its top element synchronously whenever the primary stack pops, keeping the current minimum accurate.
Inputs containing negative numbers, zeros, and positive numbers
How to Handle:
Comparison logic relies on relational operators rather than absolute magnitudes, making sign transitions seamless.
0/75 completed