DSA · Patterns, not puzzles
How do stacks and queues work?
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.
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;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
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;
}Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How would you implement a queue with two stacks?
- 2What is a monotonic stack?
- 3Why is array shift O(n)?
- 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.