Stack vs Queue — What's the Difference?
A stack is a Last-In-First-Out (LIFO) data structure where the most recently added item is removed first; a queue is First-In-First-Out (FIFO), where the earliest added item is removed first.
Published October 4, 2026
A stack is last-in, first-out (LIFO) like a pile of plates; a queue is first-in, first-out (FIFO) like a line at a shop. They differ in which end you remove from.
The concept
Stack operations: push adds to the top, pop removes the top. It models undo history, call stacks and backtracking.
Queue operations: enqueue adds to the back, dequeue removes from the front. It models task scheduling, buffering and breadth-first search.
Add 1, 2, 3 then remove one
Practical examples
Stack with an array
const stack = []
stack.push(1); stack.push(2)
stack.pop() // 2Queue (use a real deque for speed)
const queue = []
queue.push(1); queue.push(2)
queue.shift() // 1Balanced brackets with a stack
function ok(s) {
const st = [], m = { ')': '(', ']': '[' }
for (const c of s) {
if ('([').includes(c)) st.push(c)
else if (m[c] && st.pop() !== m[c]) return false
}
return st.length === 0
}Common mistakes
- Using array.shift() on huge arrays as a queue (O(n)).
- Mixing up which end gets removed.
- Forgetting to check for empty before pop/dequeue.
Key takeaways
- Stack = LIFO, queue = FIFO.
- Stacks for undo, recursion, parsing; queues for scheduling and BFS.
- Both give O(1) add and remove with the right structure.
FAQ
What is a deque?
A double-ended queue allowing add and remove at both ends.
What is a priority queue?
A queue that returns the highest-priority item first, often built on a heap.