Stack

Basic Algorithms
≈ 2 min read

Last in, first out

A stack follows the LIFO (Last In, First Out) principle: the last element added is the first one returned. It has one active side — the top. A new element is placed on the top, and removal also happens only from the top.

Deque<String> stack = new ArrayDeque<>();

stack.push("A");
stack.push("B");
stack.push("C");

String top = stack.peek(); // C
String removed = stack.pop(); // C

After removing C, B becomes the top again. The push, peek, and pop operations on ArrayDeque are amortized O(1).

A stack as memory of unfinished work

A stack is useful when newer actions temporarily cover older ones and we need to return to them in reverse order. For example, we can keep values until a reason appears to process the most recent one. This makes a stack a natural choice for nested structures and problems where the history of recent steps matters.

Stacks in Java

In modern Java code, algorithms usually use the Deque interface with ArrayDeque as its implementation. The Stack class still exists, but it is based on the older Vector design and is normally unnecessary for new solutions.

Do not call pop() on an empty stack. If an empty stack is possible in the problem logic, check isEmpty() first.