🧩 Patterns

Stack

LIFO — push, pop, peek. Used for brackets, undo, monotonic patterns

A stack processes items last-in-first-out. Classic interview uses: validate brackets, calculate expression, find next greater element. In Java use ArrayDeque, never Stack<T>.

Language:
Python
Loading...

All languages — Basic push / pop / peek

JavaScript
// JS: array as stack
const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.at(-1)); // peek → 3
stack.pop();               // pop → 3
console.log(stack);        // [1, 2]
console.log(stack.length === 0); // isEmpty → false
TypeScript
const stack: number[] = [];
stack.push(1);
stack.push(2);
stack.push(3);
const top = stack.at(-1);  // peek → 3
stack.pop();
console.log(stack);
Java
// Java: use ArrayDeque — NOT Stack<T> (it's synchronized and slow)
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);   // addFirst
stack.push(2);
stack.push(3);
stack.peek();    // 3 (top, no remove)
stack.pop();     // 3 (removes)
stack.isEmpty(); // false
stack.size();    // 2
Go
package main
import "fmt"

func main() {
    // Go: slice as stack
    stack := []int{}
    stack = append(stack, 1) // push
    stack = append(stack, 2)
    stack = append(stack, 3)
    top := stack[len(stack)-1]           // peek
    stack = stack[:len(stack)-1]         // pop
    fmt.Println(top, stack, len(stack) == 0)
}
C++
#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> st;
    st.push(1);
    st.push(2);
    st.push(3);
    cout << st.top() << endl; // peek → 3
    st.pop();                 // removes 3
    cout << st.empty() << endl; // false
    cout << st.size() << endl;  // 2
}