POST 1 of 5 MorningDSAConcept
Stack vs queue — LIFO vs FIFO
Two of the most-used structures in computer science, and the difference between them is a single sentence. A stack is Last-In-First-Out. The most recently added item is the next one to come out. Like a stack of plates — you take the top one off, you put new ones on top. A queue is First-In-First-Out. The earliest added item is the next one to come out. Like a line at a coffee shop — first in line, first served. Both structures support two operations. For a stack, push (add to top) and pop (remove from top). For a queue, enqueue (add to back) and dequeue (remove from front). Both are O(1). Where they show up. Stacks — function calls (the call stack). Undo/redo (recent action goes on top). DFS (depth-first traversal — push neighbours, pop one off, recurse). Expression parsing (operator precedence, balanced parentheses). Backtracking algorithms. Queues — BFS (breadth-first traversal — enqueue neighbours, dequeue the front). Task scheduling (jobs in submission order). Producer-consumer patterns. Async event loops. Message queues like Kafka, RabbitMQ. In Python: For a stack — use list. append() pushes; pop() removes from the end. O(1) on both. The list IS a stack. For a queue — use collections.deque, NOT list. append() and popleft() are both O(1). list.pop(0) is O(n) because it shifts all elements left. This is the most common Python perf bug I see in junior code. The rule — pick by access pattern, then pick by Python's right structure. Stack = list. Queue = deque. Don't conflate them.
#DSA#DataStructures#Algorithms#Python#100DaysOfCode#StackQueue