Question presented to candidate: "What is the difference between a stack and a queue? Give me a real use for each, and tell me which Python types you would use to implement them and what each operation costs."
What a strong answer should cover:
- LIFO versus FIFO, with the operation names (push, pop, peek; enqueue, dequeue).
- All core operations are O(1), and why a queue needs a structure that is cheap at both ends.
- Concrete uses: call stack, undo, bracket matching and DFS for stacks; BFS, scheduling and buffers for queues.
- Related structures: deque, priority queue, circular buffer, a queue built from two stacks.
- Python specifics: a
listis a fine stack (append/pop), but a queue needscollections.deque(append/popleft), becauselist.pop(0)is O(n);queue.Queueis for threads, andheapqfor priority queues.
Code / implementation expected: Optional โ using the right Python built-ins, or a short undo or round-robin example.