Skip to content

Latest commit

 

History

History
53 lines (45 loc) · 946 Bytes

155.min-stack.md

File metadata and controls

53 lines (45 loc) · 946 Bytes

Clarification Questions

  • No, it's clear from problem description.

Test Cases

Normal Cases

Input: 
Output: 

Edge / Corner Cases

Input: 
Output: 

We keep the peek value and current min via using two stack, and manipulate at the same time.

// 1. Value stack
// 2. Minimum stack
|-2| |-3|
|-1| |-3|
|-3| |-3|
| 0| | 0|
|__| |__|
class MinStack() {
    private val valueStack = Stack<Int>()
    private val minStack = Stack<Int>()

    fun push(`val`: Int) {
        valueStack.push(`val`)
        if (minStack.isEmpty()) {
            minStack.push(`val`)
        } else {
            minStack.push(if (minStack.peek() > `val`) `val` else minStack.peek())
        }
    }

    fun pop() {
        valueStack.pop()
        minStack.pop()
    }

    fun top(): Int = valueStack.peek()
    fun getMin(): Int = minStack.peek()
}