Stacks and Queues
Use stacks for last-in-first-out problems like bracket matching and undo, use queues for first-in-first-out processing, and implement both efficiently.
Welcome back!
Step 1 of 10Learn
Last in, first out
A stack works like a stack of plates: you add to the top and take from the top. The last item pushed is the first one popped, a rule called LIFO (last in, first out). A stack supports three main operations, all O(1):
- push(x): add x to the top.
- pop(): remove and return the top item.
- peek(): look at the top item without removing it.
In JavaScript, an array is already a good stack: push adds to the end and pop removes from the end, both amortized O(1).
Stacks appear everywhere once you look:
- The call stack tracks active function calls; each call is pushed, and returning pops it.
- Undo in editors pushes each action; undo pops the most recent one.
- A browser's back button keeps visited pages on a stack.
- Matching brackets in code: push each opening bracket, and when a closing one appears, it must match the top of the stack.
- Depth-first search explores a graph using a stack, either explicitly or through recursion.
- Expression evaluation: calculators convert and evaluate arithmetic using stacks.
The pattern to recognize: when the most recent unfinished thing must be dealt with first, you want a stack.
Step 2 of 10Practice · Choose one
Starting with an empty stack, you push 1, push 2, push 3, pop, push 4, pop, pop. What remains on the stack?
Step 3 of 10Learn
First in, first out
A queue works like a line at a ticket counter: people join at the back and leave from the front. The first item added is the first removed: FIFO (first in, first out). Its operations are:
- enqueue(x): add x to the back.
- dequeue(): remove and return the front item.
- peek(): look at the front item.
All should be O(1). Queues model anything processed in arrival order: print jobs, requests to a web server, messages between programs, keyboard input buffers, and breadth-first search, which explores a graph level by level.
Implementing a queue efficiently takes a little care. Using a JavaScript array with push to enqueue and shift to dequeue works, but shift moves every remaining element forward, making each dequeue O(n). For small queues this doesn't matter; for a queue of a million items processed in a loop, it turns linear work into quadratic.
Three efficient approaches:
- Head index: keep the array and an index of the front element; dequeue just reads arr[head] and increments head. Occasionally compact the array.
- Linked list with head and tail pointers: enqueue at the tail, dequeue at the head, both O(1).
- Circular buffer: a fixed-size array where the front and back indices wrap around to the start using the modulo operator.
A deque (double-ended queue) allows adding and removing at both ends in O(1), combining stack and queue behavior.
Step 4 of 10Practice · Code challenge
Write isBalanced(s) that returns true if every bracket in the string s is properly matched and nested, using the pairs (), [] and {}, and false otherwise. Ignore all other characters.
isBalanced("([]{})")isBalanced("([)]")isBalanced("((")isBalanced("f(a[1]) { return x; }")isBalanced("")isBalanced(")(")
Step 5 of 10Learn
Circular buffers and choosing the right tool
A circular buffer, or ring buffer, implements a fixed-capacity queue in an array without ever shifting elements. It keeps a head index for the front and a size count. The back is at (head + size) mod capacity. Enqueue writes there and increases size; dequeue reads at head, then moves head forward with head = (head + 1) mod capacity. When an index runs past the end of the array, the modulo wraps it back to 0.
With capacity 8, if head is at 6 and you dequeue three items, head moves 6 → 7 → 0 → 1. Circular buffers are used in audio processing, network drivers, logging the last N events and anywhere memory must stay bounded.
How do you decide between a stack and a queue? Ask what order the problem needs:
- Most recent first (nested structure, backtracking, undo, going deep): stack.
- Oldest first (fairness, processing in arrival order, going level by level): queue.
- Most important first, regardless of arrival: a priority queue, usually built on a heap, which you'll meet in a later lesson.
Many algorithms change character entirely by swapping one for the other. Graph search with a stack explores deeply along one path before backtracking; the same code with a queue explores in widening rings and finds shortest paths in unweighted graphs.
Step 6 of 10Practice · Sort into groups
Which structure fits each situation?
Tap an item, then tap its group (or drag it there).
Step 7 of 10Note
Step 8 of 10Practice · True or false
Using a JavaScript array with push() to enqueue and shift() to dequeue gives an O(1) dequeue operation.
Step 9 of 10Practice · Work it out
A circular buffer has capacity 10. The head index is 8 and the queue holds 5 items. At what array index will the next enqueued item be written?
Step 10 of 10Practice · Choose one
A printer receives jobs from many users and must print them in the order they were submitted. Which data structure and operations should it use?
Lesson complete!