# O(1) Stack

How would you design a stack which, in addition, to push and pop, also has a function min which returns the minimum element?

Push, pop and min should all operate in O(1) time.

{% tabs %}
{% tab title="Scala" %}

```scala
/**
  * 3.2
  * @param value
  * @param min
  */
case class Frame(value: Int, min: Int)

class Stack {
  var elems:List[Frame] = Nil
  def push(elem: Int): Unit = this.elems = this.elems match {
    case Nil => Frame(elem, elem) :: this.elems
    case _ => Frame(elem, elems.head.min min elem) :: this.elems
  }
  def pop: Int = this.elems match {
    case Nil => -1
    case x :: xs => {
      this.elems = xs
      x.value
    }
  }
  def min: Int = this.elems match {
    case Nil => -1
    case x :: xs => x.min
  }
}

val s = new Stack
s.push(5)
s.push(3)
s.push(99)
s.min
s.pop
s.pop
s.min
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/o-1-stack.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
