Intermediate·Concept·2 min read

Stack and queue in Python

Practice this question

Stack

Python
stack = []
stack.append(1)
stack.append(2)
stack.pop()

Queue

Python
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.popleft()

Problems to practice

  • Valid Parentheses
  • Min Stack
  • Daily Temperatures
  • Sliding Window Maximum
  • Largest Rectangle in Histogram
  • Implement Queue Using Stack

Example: valid parentheses

Python
def is_valid(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}

    for ch in s:
        if ch in '([{':
            stack.append(ch)
        else:
            if not stack or stack.pop() != pairs[ch]:
                return False

    return not stack

Adapted from 18_DSA_PYTHON.md · “5. Stack and queue in Python”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.