What is the difference between a stack and a queue?
A stack follows last in first out, so the most recently added item is removed first, like a pile of plates. A queue follows first in first out, so the earliest added item is removed first, like a line at a counter. Stacks use push and pop, queues use enqueue and dequeue.
Stack: last in first out
You add and remove from the same end, called the top. The last plate you put on the pile is the first one you take off. Stacks power the undo button, function call handling, and expression evaluation.
stack = []
stack.append(1) # push
stack.append(2)
stack.pop() # removes 2 (last in)
Queue: first in first out
You add at the back and remove from the front. The first person in line is served first. Queues power task scheduling, printers, and breadth first search.
from collections import deque
q = deque()
q.append(1) # enqueue
q.append(2)
q.popleft() # removes 1 (first in)
A common follow up is a real use case. Say a stack for undo and function calls, and a queue for scheduling and breadth first search. Concrete examples show you understand why they exist.
Common follow up questions
Related interview questions
Want the full DSA guide?
Read every DSA concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the DSA guide All DSA questions