Problem Statement
How do you implement a stack and a queue in Python? Discuss complexity and when to use each.
Explanation
A stack uses list append and pop for LIFO; both are O(1) average at the right end. It is ideal for undo, parsing, and depth-first search where last-in comes out first.
A queue should use collections.deque for FIFO; append at the right and popleft at the left are O(1). Lists are inefficient for popleft because shifting is O(n). Use queues for breadth-first search, task scheduling, and producer consumer pipelines.
Code Solution
SolutionRead Only
# stack stack=[]; stack.append(1); stack.append(2); stack.pop() # queuerom collections import deque q=deque([1,2]); q.append(3); q.popleft()
