LeetCode Grinding
Data Structures1 min read

Introduction to Stacks

A stack removes the most recently added item first, which helps with matching, reversal, and nested operations.

Stacks appear in function calls, undo and redo histories, and expression evaluation. The useful rule is LIFO, or Last In, First Out: the most recently added item is removed first.

LIFO in practice

A stack adds and removes items at the same end. Here, a JavaScript array holds the items, and its last element is the top of the stack.

javascript
class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    return this.items.pop();
  }

  peek() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }
}

For matching brackets, the last opening bracket must match the next closing bracket:

javascript
function isValidParentheses(s) {
  const stack = [];
  const pairs = { "(": ")", "[": "]", "{": "}" };

  for (let char of s) {
    if (pairs[char]) {
      stack.push(char); // Opening bracket
    } else {
      if (stack.length === 0) return false;
      const last = stack.pop();
      if (pairs[last] !== char) return false;
    }
  }

  return stack.length === 0;
}

To reverse an order, I push each item and pop them later:

javascript
function reverseString(str) {
  const stack = [];
  for (let char of str) {
    stack.push(char);
  }

  let reversed = "";
  while (stack.length > 0) {
    reversed += stack.pop();
  }
  return reversed;
}

For undo behavior, I store previous states in a stack:

javascript
class Editor {
  constructor() {
    this.content = "";
    this.undoStack = [];
  }

  type(text) {
    this.undoStack.push(this.content); // Save state
    this.content += text;
  }

  undo() {
    if (this.undoStack.length > 0) {
      this.content = this.undoStack.pop();
    }
  }
}

Complexity and fit

For a stack backed by a dynamic array, push is amortized O(1) and pop is O(1). Storing n items takes O(n) space.

I use a stack when the most recent unfinished item is the one to handle next. In the bracket example, that item is the last opening bracket that has not been closed.

Filed under

Thanks for reading

What do you think?

Leave a reaction or a comment below.

Loading reactions…

Share this post

Loading comments...

Related posts

All writing