DEV Community

Nitinn S Kulkarni
Nitinn S Kulkarni

Posted on

Part 3: Stacks and Queues โ€“ Core Concepts and Python Implementations

๐Ÿš€ Introduction

Stacks and queues are two of the most fundamental data structures in computer science.

They are the backbone of:

  • Expression evaluation (infix, postfix)

  • Backtracking algorithms

  • Tree and graph traversals

  • Task scheduling and async operations

In this post, weโ€™ll cover:

โœ… What stacks and queues are

โœ… Pythonic implementations using list and collections.deque

โœ… Real-world problems and patterns

โœ… Best practices and interview tips

๐Ÿ“ฆ 1๏ธโƒฃ What is a Stack? (LIFO โ€“ Last In, First Out)

Think of a stack of plates โ€” you can only remove or add from the top.

๐Ÿ”น Basic Operations:

- push: Add to top

- pop: Remove from top

- peek: See top item

- is_empty: Check if empty
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Python Implementation:


stack = []

stack.append(1)     # push
stack.append(2)
print(stack.pop())  # 2
print(stack[-1])    # peek โ†’ 1

Enter fullscreen mode Exit fullscreen mode

โœ… Pythonโ€™s list provides all you need for stack operations.

๐Ÿ“š Real-World Stack Use Cases

- Undo/Redo systems

- Backtracking (maze, Sudoku)

- Balanced parentheses checking

- Function call stack (recursion)
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Example: Valid Parentheses


def is_valid_parentheses(s):
    stack = []
    mapping = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in mapping.values():
            stack.append(char)
        elif char in mapping:
            if not stack or stack.pop() != mapping[char]:
                return False
    return not stack

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ 2๏ธโƒฃ What is a Queue? (FIFO โ€“ First In, First Out)

Think of a line at the bank โ€” the first person in is the first one served.

๐Ÿ”น Basic Operations:

- enqueue: Add to rear

- dequeue: Remove from front

- peek: View front item
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Python Implementation with deque:


from collections import deque

queue = deque()

queue.append(1)       # enqueue
queue.append(2)
print(queue.popleft())  # dequeue โ†’ 1

Enter fullscreen mode Exit fullscreen mode

โœ… deque is preferred for performance: O(1) operations from both ends.

๐Ÿงญ Real-World Queue Use Cases

- Breadth-first search (BFS) in trees and graphs

- Task scheduling (OS, threads, async)

- Buffering data streams

- Print job queues
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Example: BFS in a Binary Tree


from collections import deque

def bfs(root):
    if not root:
        return
    queue = deque([root])
    while queue:
        node = queue.popleft()
        print(node.val)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

Enter fullscreen mode Exit fullscreen mode

๐Ÿงช 3๏ธโƒฃ Interview-Favorite Problems

Problem Data Structure Pattern
Valid Parentheses Stack Matching pairs
Min Stack Stack Track min values
Daily Temperatures Stack Monotonic stack
BFS Traversal Queue Level-order
Rotten Oranges Queue BFS in grid
Design Circular Queue Queue Array + Pointers

๐Ÿ”ง 4๏ธโƒฃ Implementing a Min Stack


class MinStack:
    def __init__(self):
        self.stack = []
        self.min_stack = []

    def push(self, val):
        self.stack.append(val)
        min_val = val if not self.min_stack else min(val, self.min_stack[-1])
        self.min_stack.append(min_val)

    def pop(self):
        self.stack.pop()
        self.min_stack.pop()

    def top(self):
        return self.stack[-1]

    def get_min(self):
        return self.min_stack[-1]

Enter fullscreen mode Exit fullscreen mode

โœ… All operations in O(1) time.

โœ… Best Practices

โœ”๏ธ Use deque for queues and double-ended operations

โœ”๏ธ Donโ€™t use list.pop(0) for queues โ€” itโ€™s O(n)

โœ”๏ธ Know stack vs queue behavior clearly โ€” it affects algorithm choice

โœ”๏ธ Watch out for edge cases: empty stack/queue, null root, etc.

โœ”๏ธ Practice problems with state tracking and multi-level logic (e.g., BFS + levels)

๐Ÿง  Summary

โœ”๏ธ Stacks (LIFO) and queues (FIFO) solve real-world ordering and traversal problems
โœ”๏ธ Python provides clean abstractions using list and deque
โœ”๏ธ Learn core patterns like parentheses validation, BFS, and monotonic stacks
โœ”๏ธ Mastering these unlocks tree/graph algorithms and many classic interview questions

๐Ÿ”œ Coming Up Next:

๐Ÿ‘‰ Part 4: Hash Maps and Sets โ€“ Frequency Maps, Lookups, and Real-World Applications

Weโ€™ll cover:

1. Counter, defaultdict, set

  1. Grouping anagrams

  2. Sliding window with hash map

  3. Interview favorites: 2-sum, longest substring, etc.

Enter fullscreen mode Exit fullscreen mode




๐Ÿ’ฌ Whatโ€™s your favorite stack/queue trick? Got stuck on a BFS problem? Drop your questions below! ๐Ÿ”๐Ÿ“ค

Top comments (0)