What is the difference between a stack and a queue?
Why Interviewers Ask This
This is a classic screening question for Data Structures & Algorithms roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
Both are linear, abstract data types, but they differ in how elements are removed: Stack (LIFO — Last In, First Out): elements are added to and removed from the same end (top). Push adds to top, pop removes from top. Like a stack of books — you can only take from the top. Use when: you need to reverse a sequence, match brackets, track function calls, handle backtracking. Queue (FIFO — First In, First Out): elements are added to the back (rear) and removed from the front. Enqueue adds to rear, dequeue removes from front. Like a queue of people — first in, first served. Use when: you need to process things in order of arrival, BFS traversal, scheduling. Key comparison: Stack = most recent first; Queue = oldest first. Both support O(1) push/enqueue and pop/dequeue. Can implement each with the other: (1) Queue using two stacks: enqueue pushes to stack1; dequeue: if stack2 empty, pop all from stack1 to stack2, then pop from stack2. Amortized O(1) per operation; (2) Stack using two queues: push to empty queue, then dequeue all from other to it. O(n) push, O(1) pop. Common interview question: implement one using the other.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Data Structures & Algorithms experience.