8-Line Single Stack Time O(1) for all 4 operations


  • 7
    L
    public class MinStack {
        private readonly Stack<long> stack = new Stack<long>();
        private long min = 0l;
        public void Push(int x){
            stack.Push((long)x - (min = stack.Count == 0 ? (long)x : min));
            if ((long)x < min) min = (long)x;
        }
        public void Pop(){
            if(stack.Peek() < 0) min -= stack.Peek();
            stack.Pop();
        }
        public int Top(){
            return stack.Peek() < 0 ? (int)min : (int)(min + stack.Peek());
        }
        public int GetMin(){
            return (int)min;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.