Skip to content

Stack and Queue

Medium ~30 min

What you'll build

A Stack class backed by an array with push/pop/peek, and a Queue class using a head/tail pointer pair for O(1) enqueue and dequeue.

Goals

  • Understand LIFO (stack) vs FIFO (queue) ordering
  • Implement core operations with correct complexity
  • Use an array as internal storage
  • Apply stacks to balanced-bracket checking

Prerequisites

  • Arrays and array methods
  • Classes or constructor functions
  • if/else conditionals

Steps

  1. 1

    Implement the Stack

    A stack is Last-In-First-Out: the last element pushed is the first popped. Use an array and push/pop from the end for O(1) operations.

    Code
    class Stack {
      constructor() { this.items = []; }
      push(value) { this.items.push(value); return this; }
      pop() { return this.items.pop(); }
      peek() { return this.items[this.items.length - 1]; }
      isEmpty() { return this.items.length === 0; }
      size() { return this.items.length; }
    }

    Expected result

    push(1).push(2).push(3); pop() returns 3; peek() returns 2.

  2. 2

    Test the Stack

    Verify LIFO behavior by pushing three values and popping them — they should come out in reverse order.

    Code
    const s = new Stack();
    s.push(1).push(2).push(3);
    console.log(s.pop()); // 3
    console.log(s.pop()); // 2
    console.log(s.pop()); // 1
    console.log(s.isEmpty()); // true

    Expected result

    Output: 3, 2, 1, true.

  3. 3

    Implement the Queue

    A queue is First-In-First-Out. Use an array with push for enqueue and shift for dequeue. (Note: shift is O(n); a production queue would use a linked list or head/tail pointers.)

    Code
    class Queue {
      constructor() { this.items = []; }
      enqueue(value) { this.items.push(value); return this; }
      dequeue() { return this.items.shift(); }
      front() { return this.items[0]; }
      isEmpty() { return this.items.length === 0; }
      size() { return this.items.length; }
    }

    Expected result

    enqueue(1).enqueue(2).enqueue(3); dequeue() returns 1.

  4. 4

    Test the Queue

    Verify FIFO behavior by enqueuing three values and dequeuing them — they should come out in the same order.

    Code
    const q = new Queue();
    q.enqueue('a').enqueue('b').enqueue('c');
    console.log(q.dequeue()); // a
    console.log(q.dequeue()); // b
    console.log(q.dequeue()); // c

    Expected result

    Output: a, b, c — same order as inserted.

  5. 5

    Apply: balanced brackets

    Use a stack to check whether a string of brackets is balanced. Push opening brackets, pop on closing brackets and verify they match.

    Code
    function isBalanced(str) {
      const stack = new Stack();
      const pairs = { ')': '(', ']': '[', '}': '{' };
      for (const ch of str) {
        if ('([{'.includes(ch)) stack.push(ch);
        else if (')]}'.includes(ch)) {
          if (stack.pop() !== pairs[ch]) return false;
        }
      }
      return stack.isEmpty();
    }
    console.log(isBalanced('([{}])')); // true
    console.log(isBalanced('([)]'));   // false

    Expected result

    ([{}]) returns true; ([)] returns false.

Try it yourself

What you learned

You implemented the two most-used linear data structures and applied a stack to a classic parsing problem — stacks underpin function calls, undo systems, and expression evaluation.

Related Resources

Related Lessons

  • Arrays

    Arrays back both structures internally.

  • Loops

    The bracket checker loops over characters.

Related Glossary

  • Stack

    Last-In-First-Out data structure.

  • Queue

    First-In-First-Out data structure.

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

  • Stack

    Last-In-First-Out data structure.

  • Queue

    First-In-First-Out data structure.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic