Stack
A stack is a LIFO structure: the last value pushed is the first value popped.
Start with this mental model
A stack is a LIFO structure: the last value pushed is the first value popped.
How it works, without unnecessary jargon
Think of a stack of plates. You add and remove from one end only.
Core operations are push, pop and peek/top. With a good implementation they are O(1).
Read the algorithm as a sequence of decisions
Push adds to the top.
Pop removes and returns the top.
Peek reads the top without removing it.
push(1), push(2), pop() returns 2.
class Stack {
#items = [];
push(value) { this.#items.push(value); }
pop() { return this.#items.pop(); }
peek() { return this.#items.at(-1); }
get size() { return this.#items.length; }
}Do not memorize the syntax. Follow the state that changes on each line and connect it to the invariant described above.
push/pop O(1)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
Good fit
- Undo/redo
- Expression parsing
- DFS and backtracking
What usually goes wrong
- Popping from an empty stack without handling it.
- Using Array.shift() and accidentally making operations O(n).
A professional answer shape
Say LIFO first, then name push/pop/peek and one real use such as call stacks or parsing.
What problem does Stack solve?
A stack is a LIFO structure: the last value pushed is the first value popped.
What should I mention about complexity?
Its typical cost here is push/pop O(1), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
What is the most common mistake?
Popping from an empty stack without handling it.