Explain the difference between stack (LIFO) and queue (FIFO) in JavaScript, list core operations, compare time complexity, and show clean O(1) implementations (array head index or two-stacks). Include practical use cases (call stack, BFS, task queue) and common pitfalls.
Stack vs Queue in JavaScript (Differences + Implementation)
Preparing for interviews?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Quick Answer
Answer
The Core Idea
A stack is LIFO (last in, first out). A queue is FIFO (first in, first out). Same elements, different removal end.
When to use which
- Stack: call stack, undo/redo, backtracking/DFS.
- Queue: task scheduling, BFS, message processing, event loops.
JAVASCRIPT
// Stack (LIFO)
function Stack() { this.items = []; }
Stack.prototype.push = function (v) { this.items.push(v); };
Stack.prototype.pop = function () { return this.items.pop(); };
Stack.prototype.peek = function () { return this.items[this.items.length - 1]; };
// Queue (FIFO) with head index (O(1) dequeue)
function Queue() { this.items = []; this.head = 0; }
Queue.prototype.enqueue = function (v) { this.items.push(v); };
Queue.prototype.dequeue = function () {
if (this.head >= this.items.length) return undefined;
const v = this.items[this.head++];
if (this.head > 50 && this.head * 2 > this.items.length) {
this.items = this.items.slice(this.head);
this.head = 0;
}
return v;
};
Queue.prototype.peek = function () { return this.items[this.head]; };
JAVASCRIPT
// Queue with two stacks (amortized O(1))
function Queue2() { this.in = []; this.out = []; }
Queue2.prototype.enqueue = function (v) { this.in.push(v); };
Queue2.prototype.dequeue = function () {
if (this.out.length === 0) {
while (this.in.length) this.out.push(this.in.pop());
}
return this.out.pop();
};
Pitfalls
Array.shift()is O(n) because it re-indexes.- If you use a head index, compact occasionally to avoid unbounded memory.
- Don't mix stack/queue semantics in the same API.
Summary
- Stack = LIFO, queue = FIFO.
- Choose based on access order: last-first vs first-first.
- Use O(1) operations with push/pop and head index (or two stacks).
Similar questions
Guides