Stack (LIFO) and Queue (FIFO) are fundamental linear data structures that differ only in removal order. Together they underpin traversal, backtracking, buffering, and scheduling.
Elements are pushed onto and popped from the top. The last element added is the first removed.
| Operation | Time |
|---|---|
| Push / Pop | O(1) |
| Peek (top) | O(1) |
stack = []
stack.append(10); stack.append(20) # push
stack.pop() # pop — 20
stack[-1] # peekElements are added at the rear and removed from the front. The first element added is the first removed.
| Operation | Time |
|---|---|
| Enqueue / Dequeue | O(1) |
| Peek (front) | O(1) |
from collections import deque
q = deque()
q.append(10); q.append(20) # enqueue
q.popleft() # dequeue — 10
q[0] # peek frontA deque supports insertion and deletion from both ends.
from collections import deque
dq = deque([1, 2, 3])
dq.append(4); dq.appendleft(0) # add right/left
dq.pop(); dq.popleft() # remove right/left
dq.rotate(2) # rotate right by 2| # | Problem | Difficulty | Technique |
|---|---|---|---|
| 155 | Min Stack | Medium | Auxiliary min-stack tracking |
| 225 | Implement Stack using Queues | Easy | Single-queue rotation |
| 1381 | Design a Stack With Increment Operation | Medium | Lazy increment array |
| # | Problem | Difficulty | Technique |
|---|---|---|---|
| 232 | Implement Queue using Stacks | Easy | Two-stack transfer |
| 622 | Design Circular Queue | Medium | Ring buffer with modulo arithmetic |
| 641 | Design Circular Deque | Medium | Circular array with front/rear pointers |