---
# System prepended metadata

title: CSPT19 Lecture 7

---

# CSPT19 Lecture 7
## [Min Stack](https://leetcode.com/problems/min-stack)
```
from collections import deque

class MinStack:

    """
    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin(); // return -3
    minStack.pop();
    minStack.top();    // return 0
    minStack.getMin(); // return -2
    
    Plan
    Use minSoFar instance property to track min element pushed onto the stack
    Search for new minSoFar if the element popped is the min
    """
    def __init__(self):
        self.stack = deque()
        self.minSoFar = float("inf")

    def push(self, val: int) -> None:
        if val < self.minSoFar:
            self.minSoFar = val
        self.stack.append(val)

    def pop(self) -> None:
        val = self.stack.pop()
        if val == self.minSoFar:
            if len(self.stack) > 0:
                self.minSoFar = min(self.stack)
            else:
                self.minSoFar = float("inf")

    def top(self) -> int:
        return self.stack[-1]

    def getMin(self) -> int:
        return self.minSoFar
```

## [Stack Using Queue](https://leetcode.com/problems/implement-stack-using-queues/)
```
from collections import deque
class MyStack:

    """
    Understand
    
    MyStack myStack = new MyStack();
    myStack.push(1);
    myStack.push(2);
    myStack.top(); // return 2
    myStack.pop(); // return 2
    myStack.empty(); // return False
    
    
    """
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue = deque()

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.queue.append(x)

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        temp = deque()
        
        while len(self.queue) > 1:
            temp.append(self.queue.popleft())
        
        lastElement = self.queue.popleft()
        self.queue = temp
        return lastElement

    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue[-1]

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return len(self.queue) == 0
```