DSA · Patterns, not puzzles

How do stacks and queues work?

Easystackqueuedata-structuresUpdated Oct 2026
Quiz this track

Short answer

A stack is last in, first out and supports push and pop. A queue is first in, first out and supports enqueue and dequeue. Both are O(1) when implemented with the right underlying structure.

The difference is which end you remove from. A stack removes the most recent item, which fits nested structures such as function calls, undo history and bracket matching. A queue removes the oldest item, which fits breadth-first search, scheduling and buffering.

js
const stack = [];
stack.push("a");
stack.push("b");
const top = stack.pop();

const queue = [];
let head = 0;
queue.push("a");
queue.push("b");
const first = queue[head];
head += 1;
Using a head index avoids the O(n) cost of shift on a JavaScript array.

Where each shows up

  • Stack: valid parentheses, undo, depth-first search, expression evaluation
  • Queue: breadth-first search, task scheduling, rate limiting
  • Deque: sliding window maximum, where both ends are used
  • Monotonic stack: next greater element and histogram problems
js
function isValid(text) {
  const pairs = { ")": "(", "]": "[", "}": "{" };
  const stack = [];
  for (const ch of text) {
    if (ch === "(" || ch === "[" || ch === "{") {
      stack.push(ch);
    } else if (ch in pairs) {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }
  return stack.length === 0;
}
The stack remembers open brackets so each closing bracket can be checked in O(1).
In JavaScript, array shift is O(n). For large queues, use a head index or a real deque implementation instead of shift.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How would you implement a queue with two stacks?
  2. 2What is a monotonic stack?
  3. 3Why is array shift O(n)?
  4. 4How does a stack help with recursion?

Say it in the interview

A stack is LIFO, so push and pop operate on the same end. A queue is FIFO, so items leave in the order they arrived. I use a stack for bracket matching and DFS, and a queue for BFS and scheduling. In JavaScript I avoid array shift for queues because it is O(n); I keep a head index instead.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.