# Stacks

## Runtime analysis

1. Top/peek: $$O(1)$$
2. Push: $$O(1)$$
3. Pop: $$O(1)$$
4. Search: $$O(n)$$
5. isEmpty: $$O(1)$$

## Corner cases

1. Empty stack
2. Stack with one item
3. Stack with two items

## Take note…

1. `pop()` is LIFO so if order of insertion matters, reverse the popped values

## Techniques

### Monotonic stack&#x20;

Push elements while monotonically increasing/decreasing. Then, keep popping the elements once the reverse occurs until either empty or incoming element is eventually increasing/decreasing

* The final stack can represent the overall values

### Mathematical equation parsing

Stacks are useful for problems like evaluating equations as you can push numbers onto the stack and operations just need to pop the top two elements of the stack


---

# 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://interviews.woojiahao.com/data-structures/stacks.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.
