Question

Formatted question description: https://leetcode.ca/all/155.html

155	Min Stack

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

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

@tag-stack

Algorithm

Two stacks are used to achieve this, one stack is used to store the data that push in in order, and the other is used to store the smallest value that has occurred.

Code

Java

  • class MinStack {
    
        Stack<Integer> sk = new Stack<>();
        Stack<Integer> min = new Stack<>();
        
        public void push(int x) {
            sk.push(x);
            // @note: if pushing duplicated, then the 2nd is missing if no "="
            if (min.isEmpty() || min.peek() >= x) {
                min.push(x);
            }
        }
    
        public void pop() {
            int popVal = sk.pop();
            if (popVal == min.peek()) {
                min.pop();
            }
        }
    
        public int top() {
            return sk.peek();
        }
    
        public int getMin() {
            return min.peek();
        }
    
    	
    }
    
    class MinStack_SortedList_ACed {
    
        Stack<Integer> sk;
        PriorityQueue<Integer> sorted;
    
        /** initialize your data structure here. */
        public MinStack_SortedList_ACed() {
            sk = new Stack<>();
            sorted = new PriorityQueue<>();
        }
    
        public void push(int x) {
            sk.push(x);
            sorted.offer(x); // NlogN
        }
    
        public void pop() {
            int popped = sk.pop();
    
            // remove by object, not by index
            // but, here remove() is o(N) operation
            sorted.remove(popped);
        }
    
        public int top() {
            return sk.peek();
        }
    
        public int getMin() {
            return sorted.peek();
        }
    }
    
    
  • // OJ: https://leetcode.com/problems/min-stack/
    // Time: O(1) for all
    // Space: O(N)
    class MinStack {
        stack<int> mn, val;
    public:
        MinStack() {}
        void push(int x) {
            val.push(x);
            if (mn.empty() || mn.top() >= x) mn.push(x);
        }
        void pop() {
            if (val.top() == mn.top()) mn.pop();
            val.pop();
        }
        int top() {
            return val.top();
        }
        int getMin() {
            return mn.top();
        }
    };
    
  • class MinStack:
    
    	def __init__(self):
    		self.sk = []
    		self.minsk = []
    
    	def push(self, val: int) -> None:
    		self.sk.append(val)
    		self.minsk.append(val if not self.minsk else min(val, self.minsk[-1]))
    
    	def pop(self) -> None:
    		if not self.sk:
    			return
    		
    		self.sk.pop()
    		self.minsk.pop()
    
    	def top(self) -> int:
    		return self.sk[-1]
    
    	def getMin(self) -> int:
    		return self.minsk[-1]
    
    # optimize above, using only 1 stack, with stack element as tuple: (val, its associated min)
    class MinStack:
    
        def __init__(self):
            self._stack = []
            
        def push(self, x: int) -> None:
            cur_min = self.getMin()
            if x < cur_min:
                cur_min = x
            self._stack.append((x, cur_min))
            
        def pop(self) -> None:
            self._stack.pop()
    
        def top(self) -> int:
            if not self._stack:
                return None
            else:
                return self._stack[-1][0]
    
        def getMin(self) -> int:
            if not self._stack:
                return float('inf')
            else:
                return self._stack[-1][1]
    
    

All Problems

All Solutions