Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

155. Min Stack

Topics: Stack Design

Solution

Implementation

class MinStack() {

    private val stack = mutableListOf<Int>()
    private val minStack = mutableListOf<Int>()

    fun push(value: Int) {
        stack.add(value)
        if (minStack.isEmpty() || value < minStack.last()) {
            minStack.add(value)
        } else {
            minStack.add(minStack.last())
        }
    }

    fun pop() {
        stack.removeLast()
        minStack.removeLast()
    }

    fun top(): Int = stack.last()

    fun getMin(): Int = minStack.last()
}