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.


MinStack minStack = new MinStack();
minStack.getMin();   -->Returns -3.
minStack.top();      -->Returns 0.
minStack.getMin();   -->Returns -2.


Linkedlist style to record the head info,

record min history by iteratively comparing the min of the current value and history min

Code (Python)

class MinStack(object):

    def __init__(self):
        initialize your data structure here.
        self.head = None

    def push(self, x):
        :type x: int
        :rtype: void
        if(self.head == None):
            self.head = Node(x, x);
            self.head = Node(x, min(self.head.min, x), self.head)

    def pop(self):
        :rtype: void
        self.head = self.head.next

    def top(self):
        :rtype: int
        return self.head.val

    def getMin(self):
        :rtype: int
        return self.head.min

class Node(object):

    def __init__(self, val, minval, next = None):
        self.val = val
        self.min = minval
        self.next = next

# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

results matching ""

    No results matching ""