# ac solution code

• ``````/*
SWIFT
Solution1. space = O(n); time:
push: O(1)
pop : O(1)
top: O(1)
getMin: O(1)

The basic idea is to use an additional minStack:
push(x):
1) if x < minStack.top, push x to  minStack.top
2) push x to stack
pop:
1) if stack.peek() == minStack.top, pop x from minStack.top
2) pop x from stack
*/
public class MinStack {
var minStack = Stack<Int>()
var stack = Stack<Int>()

public func push(_ x: Int) {
if minStack.isEmpty() || x <= minStack.peek()! {// Push x into minStack: Only when 1) minStack is empty; 2) x is smaller  than the top of minStack
minStack.push(x)
}
stack.push(x)
}

public func pop() -> Int? {
if stack.peek() == minStack.peek() {//Pop from minStack: Only when the top of stack equals the top of minStack
let _ = minStack.pop()
}
return stack.pop()
}

public func top() -> Int? {
return stack.peek()
}

public func getMin() -> Int? {
return minStack.peek()
}
}
``````

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