Some problems hand you items that can’t be settled the moment they arrive. An opening bracket waits for its partner, a folder name waits to see whether a .. cancels it, and a request waits until it’s old enough to stop counting against a limit. You need somewhere to park that unfinished work, and the order you take it back out decides which structure you want:
- A stack gives back the most recent item first: last in, first out. Use one when the newest unfinished thing is the one the next item can settle, as with nesting and undo.
- A queue gives back the oldest item first: first in, first out. Use one when items expire or get served in the order they arrived.
A Stack Is Just an Array
In JavaScript, an array with push() and pop() is already a stack, and both operations run in O(1) time. Here’s a stack keeping track of which HTML tags are still open:
const open = [];
for (const token of ["<ul>", "<li>", "</li>", "<li>"]) {
if (token.startsWith("</")) open.pop();
else open.push(token);
}
console.log(open, open.at(-1));
Each closing tag removes the tag opened most recently, so after the loop, two tags are still waiting:
[ '<ul>', '<li>' ] <li>
open.at(-1) peeks at the top without removing it. Watch out for one quiet behavior: pop() on an empty array returns undefined instead of throwing an error. If a closing item arrives when the stack is empty, check for that case yourself, or your code ends up comparing against undefined.
The cost argument is worth saying out loud in an interview. Every item is pushed once and popped at most once, so a pass over n items does O(n) stack work in total, even when a single step pops many items at once.
A Queue Needs More Care
The obvious queue in JavaScript is push() to add at the back and shift() to take from the front. It reads well, but shift() has to move every remaining item one slot forward. V8 hides that cost for small arrays, and then it shows up all at once:
function drain(size) {
const queue = Array.from({ length: size }, (_, i) => i);
const start = performance.now();
while (queue.length > 0) queue.shift();
return performance.now() - start;
}
const ratio = drain(100_000) / drain(10_000);
console.log(ratio > 100 ? "over 100 times slower" : "about 10 times slower");
Exact times vary, but the ratio lands far above 100:
over 100 times slower
Ten times as many items took more than a hundred times as long. That’s O(n²) work hiding inside a loop that looks linear, and it’s exactly the follow-up an interviewer asks about once your code works.
The fix is to stop moving items. Keep a head index that points at the front of the queue, and read from it instead of shifting:
const queue = [];
let head = 0;
for (const id of ["r1", "r2", "r3"]) queue.push(id);
const first = queue[head++];
console.log(first, queue.length - head);
The queue served its oldest item, and two items are still waiting:
r1 2
Taking an item is now O(1). The array keeps the slots you’ve already served, which is fine for a single pass. A long-running queue can trim them once head passes half the array.
When to Reach for Each One
Listen for these clues:
- Nesting or matching: brackets, tags, folders, and undo all mean that the most recent open item is the next one to close. That’s a stack.
- The next bigger or smaller value: keep a stack of items that are still waiting for an answer. When a new value settles some of them, pop them off and record their answers.
- Time windows and arrival order: rate limits and “the last N seconds” mean the oldest item leaves first. That’s a queue.
In this section, you’ll check brackets in code snippets, replay keystrokes, clean up URL paths, and find how long each price waits for a higher one. In each exercise, ask yourself what’s still unfinished and which of those items the next input settles.