Skip to content

Latest commit

 

History

History
56 lines (36 loc) · 724 Bytes

File metadata and controls

56 lines (36 loc) · 724 Bytes

Min Stack

Problem Link

https://leetcode.com/problems/min-stack/


Pattern

  • Stack
  • Design

Approach

Store the current minimum alongside each pushed value so getMin stays O(1).


Time Complexity

O(1) per operation

Space Complexity

O(n)


Java Solution

import java.util.*;
class MinStack {
    private Stack<int[]> stack = new Stack<>();

    public void push(int val) {
        int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
        stack.push(new int[]{val, min});
    }

    public void pop() {
        stack.pop();
    }

    public int top() {
        return stack.peek()[0];
    }

    public int getMin() {
        return stack.peek()[1];
    }
}