A2Z Lesson

Log in
← Back to the A2Z sheet

Step 12 Stack / Queues — Implementation

Implementation using different DS

Medium

Stacks and queues are defined by their interfaces — LIFO and FIFO — not by how they are stored. This lesson is about building one structure out of another: a stack from two queues, a queue from two stacks, and both from arrays and linked lists. The point is fluency with the interfaces and honest cost analysis, including the amortised argument that makes the two-stack queue O(1) per operation even though one operation occasionally does O(n) work.

The interfaces you must preserve

A stack offers push, pop, peek/top and isEmpty, all conceptually O(1), with last-in-first-out order. A queue offers enqueue (add at back), dequeue (remove from front), front/peek and isEmpty, all O(1), with first-in-first-out order.

An implementation is correct if the observable behaviour matches the interface, whatever happens inside. That freedom is what makes 'implement a queue using stacks' a meaningful exercise: internally you may move elements around, as long as dequeue returns elements in arrival order.

Queue from two stacks (amortised O(1))

Keep an inbox stack and an outbox stack. Enqueue pushes onto inbox. Dequeue pops from outbox; if outbox is empty, first pour all of inbox into outbox (which reverses the order, putting the oldest element on top), then pop.

Why is this fast overall? Each element is pushed twice and popped twice in its entire lifetime — once in inbox, once in outbox. The expensive pour moves each element exactly once, so over n operations the total work is O(n): amortised O(1) per operation, even though a single dequeue after many enqueues costs O(n) once.

class QueueUsingStacks: def __init__(self): self.inbox = [] self.outbox = [] def enqueue(self, x): self.inbox.append(x) def _pour(self): while self.inbox: self.outbox.append(self.inbox.pop()) def dequeue(self): if not self.outbox: self._pour() return self.outbox.pop() if self.outbox else None def front(self): if not self.outbox: self._pour() return self.outbox[-1] if self.outbox else None

Stack from queues, and the cost trade-off

With two queues (or even one), you choose which operation pays. Push-costly version: enqueue the new element, then rotate all older elements behind it, so the front of the queue is always the stack top — push is O(n), pop is O(1). Pop-costly version: enqueue is O(1) (just append at the back), and pop rotates all but the last element into the helper queue, removes the last, then swaps the queues' roles — pop is O(n).

There is no way to make both O(1) with plain queues; the exercise teaches you to read which operation the problem makes frequent and pay the cost on the other one.

from collections import deque class StackUsingQueue: # push-costly variant: pop and top are O(1) def __init__(self): self.q = deque() def push(self, x): self.q.append(x) for _ in range(len(self.q) - 1): self.q.append(self.q.popleft()) # rotate old elements behind x def pop(self): return self.q.popleft() if self.q else None def top(self): return self.q[0] if self.q else None

Array-based and linked-list-based versions

Stack from an array: a top index; push writes at ++top, pop reads at top--. Watch overflow (fixed capacity) and underflow (popping empty). Queue from an array: a linear array wastes the slots freed at the front, so real implementations are circular — front and rear advance modulo capacity, with one slot (or a size counter) used to distinguish full from empty. Both directions of index arithmetic are classic off-by-one sources.

Linked-list versions remove capacity limits: a stack pushes/pops at the head (O(1), never use the tail); a queue enqueues at a maintained tail pointer and dequeues at the head, both O(1). Forgetting to update the tail pointer when the last element is dequeued is the standard bug — the next enqueue then attaches to a dead node.

Complexity summary and mistakes

Array stack/queue: O(1) per op, fixed capacity, circular indexing for queues. Linked-list versions: O(1) per op, O(n) total extra space in pointers, no capacity limit. Two-stack queue: amortised O(1), worst-case single op O(n). Two-queue stack: one operation is O(n) by design.

Common mistakes: pouring the inbox into the outbox while outbox still has elements (destroys order — only pour when outbox is empty); rotating the wrong count in the stack-from-queue push; and answering 'queue from two stacks is O(1)' without the word amortised in an interview.

Key points

  • Implementations must preserve the interface (LIFO / FIFO), not any particular internal layout.
  • Queue from two stacks: pour inbox into outbox only when outbox is empty; each element moves once, giving amortised O(1).
  • Stack from queues: either push or pop must pay O(n) — choose based on which operation dominates.
  • Array queues should be circular; linked-list queues need both head and tail pointers kept in sync.
  • Always state amortised vs worst-case honestly — a single two-stack dequeue can cost O(n).

Suggested questions

Implement Stack using Arrays ↗ The base case: top pointer, overflow and underflow checks.
Implement Queue using Stack ↗ The two-stack queue and its amortised argument, as a coding drill.
Implement Stack using Queue ↗ The push-costly rotation trick from this lesson.
Implement stack using Linkedlist ↗ Push/pop at the head only — the tail is a trap.
Implement queue using Linkedlist ↗ Head for dequeue, tail for enqueue; keep the tail pointer correct on the last removal.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.