Stacks — Implementation & Applications
📖 Concept
A stack is a LIFO (Last In, First Out) data structure. Think of a stack of plates — you add and remove from the top only.
Operations — ALL O(1):
- push(item) — Add to top
- pop() — Remove and return top
- peek()/top() — View top without removing
- isEmpty() — Check if stack is empty
Where stacks appear in the real world:
- Call stack — function execution tracking
- Undo/Redo — text editors, Ctrl+Z
- Browser back button — history of visited pages
- Expression evaluation — parentheses matching, postfix notation
- DFS traversal — iterative DFS uses an explicit stack
Classic interview patterns using stacks:
- Valid parentheses — push opening, pop on closing, check match
- Next greater element — monotonic stack
- Min stack — O(1) getMin using auxiliary stack
- Evaluate postfix expression — push numbers, pop on operators
- Daily temperatures — monotonic decreasing stack
🏠 Real-world analogy: A Pringles can — you can only access the chip on top. To get to the bottom chip, you must remove all above it.
💻 Code Example
1// STACK — Array-based implementation2class Stack {3 constructor() {4 this.items = [];5 }6 push(item) { this.items.push(item); }7 pop() { return this.items.pop(); }8 peek() { return this.items[this.items.length - 1]; }9 isEmpty() { return this.items.length === 0; }10 size() { return this.items.length; }11}1213// VALID PARENTHESES — Classic stack problem14function isValid(s: string): boolean {15 const stack: string[] = [];16 const map: Record<string, string> = { ')': '(', '}': '{', ']': '[' };1718 for (const char of s) {19 if ('({['.includes(char)) {20 stack.push(char);21 } else {22 if (stack.pop() !== map[char]) return false;23 }24 }25 return stack.length === 0;26}2728// MIN STACK — O(1) push, pop, getMin29class MinStack {30 private stack: number[] = [];31 private minStack: number[] = [];3233 push(val: number): void {34 this.stack.push(val);35 const min = this.minStack.length === 036 ? val37 : Math.min(val, this.minStack[this.minStack.length - 1]);38 this.minStack.push(min);39 }4041 pop(): void {42 this.stack.pop();43 this.minStack.pop();44 }4546 top(): number { return this.stack[this.stack.length - 1]; }47 getMin(): number { return this.minStack[this.minStack.length - 1]; }48}4950// NEXT GREATER ELEMENT — Monotonic stack51function nextGreater(arr: number[]): number[] {52 const result = new Array(arr.length).fill(-1);53 const stack: number[] = []; // Stack of indices5455 for (let i = 0; i < arr.length; i++) {56 while (stack.length && arr[i] > arr[stack[stack.length - 1]]) {57 result[stack.pop()!] = arr[i];58 }59 stack.push(i);60 }61 return result;62}63// [4,5,2,10,8] → [5,10,10,-1,-1]6465// EVALUATE POSTFIX — "3 4 + 2 *" = (3+4)*2 = 1466function evalPostfix(tokens: string[]): number {67 const stack: number[] = [];68 for (const token of tokens) {69 if ('+-*/'.includes(token)) {70 const b = stack.pop()!, a = stack.pop()!;71 if (token === '+') stack.push(a + b);72 if (token === '-') stack.push(a - b);73 if (token === '*') stack.push(a * b);74 if (token === '/') stack.push(Math.trunc(a / b));75 } else {76 stack.push(Number(token));77 }78 }79 return stack[0];80}
🏋️ Practice Exercise
Practice Problems (Easy → Hard):
- Implement a stack using an array (push, pop, peek, isEmpty)
- Check if parentheses are balanced: "({[]})" → true, "({)}" → false
- Reverse a string using a stack
- Implement a Min Stack with O(1) getMin
- Evaluate a postfix expression
- Convert infix to postfix expression
- Next greater element for each element in an array
- Daily temperatures: for each day, how many days until warmer?
- Implement a stack using two queues
- Largest rectangle in histogram (monotonic stack)
⚠️ Common Mistakes
Using shift/unshift for stack operations — stack should use push/pop (end of array) for O(1)
Not checking isEmpty before pop/peek — causes undefined errors
Forgetting to check stack is empty after processing — leftover elements mean invalid input
Using a stack when a simple variable/counter would suffice (e.g., just counting parentheses depth)
Not recognizing monotonic stack patterns — these are very common in interviews
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Stacks — Implementation & Applications