Skip to the solution
EasyDSA11 min read

What is the difference between a stack and a queue?

918 views

The problem

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 list is a fine stack (append/pop), but a queue needs collections.deque (append/popleft), because list.pop(0) is O(n); queue.Queue is for threads, and heapq for priority queues.

Code / implementation expected: Optional โ€” using the right Python built-ins, or a short undo or round-robin example.

  • stack
  • queue

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonSame arrivals, opposite exits
PythonUndo with a stack, round-robin with a queue

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 8 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is Big-O notation?

Continue