What is the difference between a stack and a queue, with real examples?
A stack is last in, first out (LIFO): you add and remove at the same end. A queue is first in, first out (FIFO): you add at the back and remove from the front.
Explain it simply
A stack is a pile of plates in a mess canteen. You put a plate on top and you also take from the top, so the last plate placed is the first one used.
A queue is the line at an IRCTC ticket counter. The person who joined first is served first, and new people stand at the back.
| Stack | Queue | |
|---|---|---|
| Order | LIFO | FIFO |
| Add | push (top) | enqueue (back) |
| Remove | pop (top) | dequeue (front) |
| Typical uses | undo, browser back, call stack, bracket matching, DFS | task scheduling, print jobs, BFS, buffering requests |
In JavaScript an array works as a stack with push and pop. As a queue, push and shift work, but shift is O(n) on large arrays, so a linked list or an index pointer is better for heavy use.
Example
const stack = [];
stack.push("a");
stack.push("b");
console.log(stack.pop()); // b
const queue = [];
queue.push("a");
queue.push("b");
console.log(queue.shift()); // aWhat to say in the interview
"A stack is LIFO and a queue is FIFO. A stack gives me undo, recursion and DFS; a queue gives me scheduling and BFS. Both support insert and remove in O(1) when implemented well, but array shift in JavaScript is O(n), so I would use a proper queue for large inputs."
Common mistakes
- Mixing up which end is removed: the stack removes the newest, the queue removes the oldest.
- Assuming Array.shift is O(1).