Min Stack in Java: Explanation & Practice

Design stack that supports getMin in O(1)

Problem summary

Design a stack that supports push, pop, top, and retrieving minimum element in constant time.

Starter code

public class Main {
    public static void main(String[] args) {
        // Implement MinStack
        // push(-2), push(0), push(-3)
        // getMin() → -3
        // pop()
        // top() → 0
        // getMin() → -2
        // Print operations in order
    }
}

Expected output and test cases

  • push -2,0,-3; getMin; pop; top; getMin
    Min: -3
    Top: 0
    Min: -2
  • push -2,0,-1; getMin twice
    Min: -2
    Min: -2
  • push 1; getMin
    Min: 1

Hints

  1. Use two stacks: one for values, one for minimums
  2. When pushing, also push to min stack if <= current min
  3. When popping, also pop from min stack if value equals current min
  4. Alternative: store pairs of (value, minSoFar)

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler