Stacks and queues
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Distinguish last-in-first-out from first-in-first-out behaviour.
- Use a stack to match nested structure such as brackets.
- Use a queue for level-by-level or order-preserving processing.
Overview
#Two access orders
A stack is last-in-first-out (LIFO): the most recently pushed element is popped first. A queue is first-in-first-out (FIFO): the oldest element is dequeued first. Both support O(1) insert and remove at their active end.
In JavaScript, an array works as a stack with push and pop. As a queue, shift is O(n) because it shifts every element, so prefer a dedicated deque or two-stack queue when performance matters.
Stack: matching brackets
function isBalanced(s) {
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') stack.push(ch);
else if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
}
}
return stack.length === 0;
}
Each opening bracket is pushed; each closing bracket must match the most recent opening one. That is exactly LIFO behaviour.
Queue: level order
A queue processes items in the order discovered. Breadth-first traversal of a tree or graph uses a queue so that all nodes at one distance are handled before the next level.
Monotonic stack preview
A stack that keeps its elements in sorted order can answer next-greater-element questions in O(n). When a new element arrives, pop smaller elements first; each popped element has now found its next greater element. Every element is pushed and popped once, so the total work is linear.
Practice next
- Implement a queue using two stacks and analyse the amortised cost.
- Use a monotonic stack to compute daily temperatures.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Is the string '([)]' balanced according to the bracket-matching algorithm?
starter.javascript// push '(', push '[', then see ')' while '[' is on topReveal the reference answer
reference.javascriptAfter pushing '(' and '[', the next character is ')'. The stack top is '[', which does not match ')', so the function returns false.Authored expected output: false
Correct nesting requires the most recent opening bracket to match, which is the LIFO rule.
Exercise 2Implement
Implement a stack that also returns the current minimum in O(1) time.
starter.javascriptclass MinStack { constructor() { /* ... */ } push(x) { /* ... */ } pop() { /* ... */ } top() { /* ... */ } getMin() { /* ... */ } }Reveal the reference answer
reference.javascriptclass MinStack { constructor() { this.items = []; this.mins = []; } push(x) { this.items.push(x); this.mins.push(this.mins.length ? Math.min(x, this.mins[this.mins.length - 1]) : x); } pop() { this.mins.pop(); return this.items.pop(); } top() { return this.items[this.items.length - 1]; } getMin() { return this.mins[this.mins.length - 1]; } }Authored expected output: getMin returns the smallest pushed value in O(1)
A second stack stores the running minimum at each depth, so the minimum is always on top.
Exercise 3Explain
Explain why an array is a poor queue in JavaScript.
Reveal the reference answer
reference.textRemoving the front element with shift moves every remaining element down one index to keep the array contiguous, which is O(n) per removal. A stack uses push and pop at the end, which are O(1). For queue behaviour, use a structure with an O(1) front removal, such as a deque or two stacks.Authored expected output: shift is O(n) because it reindexes all remaining elements.
Array layout makes end operations cheap and front operations expensive.
Common misconceptions
#- shift on a JavaScript array is O(1). It is O(n) because every remaining element moves down one index.
- A queue and a stack are interchangeable. The access order changes which problems they solve.
- A monotonic stack sorts the input. It maintains order among a subset of elements as they are processed.
Follow-up practice
#- dsa-from-zero-linked-lists
- dsa-from-zero-graphs-and-traversal
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.