Labs ICT
โญ Pro Login

Stacks

Last in, first out โ€” the undo button of data structures.

Stacks

Imagine a stack of plates at a buffet. You always take from the top and add to the top. That's exactly how stacks work - Last In, First Out (LIFO). The last plate you put down is the first one you pick up.

Stacks are one of the simplest yet most useful data structures. They enforce a strict order of operations, which makes them perfect for problems where you need to track "what came last." It's like having perfect memory of recent events.

You've probably used stacks without even knowing it. Every time you press Ctrl+Z, you're using a stack. Every time you navigate back in your browser, you're using a stack. They're everywhere once you start looking.

Core Operations

Two main moves: push (add to top) and pop (remove from top). Both are O(1) - instant operations. You can also peek at the top without removing it, or check if the stack is empty. Simple, elegant, effective.

Think of your browser's back button. Every page you visit gets pushed onto a stack. Click back? You pop the current page and see the previous one. The history stack keeps track of everything in order.

const stack = [];
stack.push("page1");
stack.push("page2");
stack.push("page3");
console.log(stack.pop());
console.log(stack[stack.length - 1]);
console.log(stack.length === 0);

Real-World Uses

Stacks are everywhere once you know what to look for. Undo functionality in text editors? Stack. Function call stack in programming? Stack. Evaluating math expressions? Stack. Syntax parsing in compilers? You guessed it - stack.

The call stack is especially important - it tracks which function is currently running, which function called it, and so on. Without stacks, recursive functions wouldn't work. They're the backbone of how programming languages execute code.

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5));
console.log(factorial(10));

Stack Problems

They're also great for problems like balanced parentheses validation or reversing strings. Any time you need to match things in reverse order, a stack is probably your answer. Trust me on this one.

Another classic problem is checking if a string is a palindrome using a stack. Push the first half, then compare with the second half. If they match, it's a palindrome. Simple and elegant solution.

Stacks also help with depth-first search (DFS) in graphs. You push neighbors onto the stack and explore deeply before backtracking. It's like exploring a maze - go as far as you can, then back up when you hit a dead end.

function isPalindrome(str) {
  const stack = [];
  for (let i = 0; i < str.length; i++) {
    stack.push(str[i]);
  }
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== stack.pop()) return false;
  }
  return true;
}
console.log(isPalindrome("racecar"));
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What data structure uses LIFO (Last In, First Out)?