Stacks and Queues
π Introduction
π― Stack: Last In, First Out (LIFO)
Visual Representation
Stack Implementation
from typing import Optional, Generic, TypeVar
T = TypeVar('T')
class Stack(Generic[T]):
"""
Stack implementation using Python list.
All operations O(1) amortized.
"""
def __init__(self):
self._items: list[T] = []
def push(self, item: T) -> None:
"""Add item to top. O(1) amortized."""
self._items.append(item)
def pop(self) -> T:
"""Remove and return top item. O(1)."""
if self.is_empty():
raise IndexError("Pop from empty stack")
return self._items.pop()
def peek(self) -> T:
"""Return top item without removing. O(1)."""
if self.is_empty():
raise IndexError("Peek at empty stack")
return self._items[-1]
def is_empty(self) -> bool:
"""Check if stack is empty. O(1)."""
return len(self._items) == 0
def size(self) -> int:
"""Return number of items. O(1)."""
return len(self._items)
def __len__(self) -> int:
return self.size()
def __str__(self) -> str:
return f"Stack({self._items})"
# Usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek()) # 3
print(stack.pop()) # 3
print(stack.pop()) # 2Stack Using Linked List
π Queue: First In, First Out (FIFO)
Visual Representation
Queue Implementation with Deque
Circular Queue (Fixed Size)
π Deque: Double-Ended Queue
Implementing Deque
π Stack Applications
Valid Parentheses
Evaluate Reverse Polish Notation
Min Stack
Daily Temperatures (Monotonic Stack)
π Monotonic Stack
Next Greater Element
Largest Rectangle in Histogram
Trapping Rain Water
π Queue Applications
BFS (Level Order Traversal)
Sliding Window Maximum
Task Scheduler
β Priority Queue
Kth Largest Element
Merge K Sorted Lists
π Practice Exercises
Exercise 1: Implement Queue Using Stacks
Exercise 2: Implement Stack Using Queues
Exercise 3: Simplify Path
π Key Takeaways
π What's Next?
π References
Last updated