Data Structures, Explained Like You're Five: Stacks & Queues
Two of the simplest data structures in all of computer science come down to a single question: when you take something out, which one comes out first? A stack gives you the most recent. A queue gives you the oldest. That one difference is the whole lesson.
Stacks: last in, first out
A stack is a stack of plates. You add a plate on top, and you take a plate off the top. The last one you put down is the first one you pick up — "LIFO."
Stacks are how your code remembers where it was: every function call stacks on top of the last, and the "undo" button pops the most recent thing you did.
Queues: first in, first out
A queue is a line at a store. You join at the back, and the person at the front gets served first — "FIFO." Fair and orderly.
Queues run anything that should be handled in arrival order: print jobs, task schedulers, and (as you'll see in the next post) the "to-visit" list in breadth-first search.
Why interviewers ask about them
Both are O(1) to add and remove — instant — and "which end do I take from?" is the entire insight behind a huge number of problems (matching brackets, undo/redo, scheduling). Knowing which one a problem secretly wants is often the whole solution.
Same idea, opposite door. A stack takes from the same end it adds to (top); a queue takes from the far end (front). Pick the one whose order matches your problem.