880822. Get min at pop

Easy

Here is a detailed Markdown blog post for the problem "Get min at pop":

Get Min at Pop

Summary

The "Get min at pop" problem involves designing an algorithm to find and maintain the minimum value in a stack. This problem requires understanding of basic data structures, specifically stacks, and how to efficiently manage them.

Detailed Explanation

When we say "get min at pop", it means that whenever we pop an element from the stack, we need to get the minimum element among all the elements popped so far. We can achieve this by using a secondary stack to keep track of the minimum elements.

Here's a step-by-step breakdown of the solution:

  1. Initialize two stacks: mainStack and minStack. mainStack will store the actual elements, while minStack will store the minimum elements.
  2. Push the first element from mainStack onto minStack as well, since it's the only element so far.
  3. For each subsequent push operation:
    • If the pushed element is less than or equal to the top of minStack, push it onto both stacks.
    • Otherwise, pop all elements from minStack until the top element is smaller than or equal to the pushed element. Then, push this new minimum element and the pushed element onto both stacks.
  4. For each pop operation:
    • Pop the top element from mainStack. This will be the element we're interested in.
    • Find the minimum of all elements popped so far by popping and comparing the top elements from minStack until we find the minimum. This is our answer.

Time Complexity: O(n), where n is the number of push/pop operations. Space Complexity: O(n), since we need to store at most n-1 elements in both stacks.

Optimized Solutions

Java

View on GeeksforGeeks
class GetMinAtPop {
    public static int getMin(Stack<Integer> mainStack) {
        Stack<Integer> minStack = new Stack<>();
        int min = mainStack.pop();
        minStack.push(min);
        for (int x : mainStack) {
            if (x <= min) {
                min = x;
                minStack.push(x);
                mainStack.push(x);
            } else {
                while (!minStack.isEmpty() && minStack.peek() > x) {
                    minStack.pop();
                }
                minStack.push(min);
                mainStack.push(x);
            }
        }
        return min;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.