Skip to content
Chethan Yadav_
Data Structures & Algorithms

DSA/Lesson 4 of 11/4 min read

Stacks and Queues

Stack and queue operations, deque, circular queue, monotonic stack and queue, and expression evaluation.


On this page

Stack

LIFO: last in, first out. Operations push, pop, peek, all O(1).

Implementations: dynamic array (most common), or a linked list pushing at the head.

Where stacks appear:

  • Function call stack and recursion.
  • Undo in editors, browser back button.
  • Balanced parentheses, expression parsing.
  • Iterative DFS.

Balanced parentheses

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack

Min stack

Support getMin in O(1): push (value, current_min) pairs, or keep a second stack of minimums.

Queue

FIFO: first in, first out. Operations enqueue, dequeue, front, all O(1).

Pitfall: using a Python list with pop(0) is O(n). Use collections.deque.

Where queues appear: BFS, task scheduling, print spoolers, message buffers, rate-limited pipelines.

Queue using two stacks

Push to in_stack. On dequeue, if out_stack is empty, move everything from in_stack to out_stack. Each element moves at most once, so dequeue is O(1) amortized.

Circular Queue

A fixed-size array with front and rear indices that wrap using modulo. Avoids shifting and wasted space at the front.

enqueue: rear = (rear + 1) % capacity
dequeue: front = (front + 1) % capacity

Distinguish full from empty by keeping a size counter (or leaving one slot empty). Used in ring buffers for audio, network drivers and logging.

Deque

Double-ended queue: insert and remove at both ends in O(1). Python collections.deque, Java ArrayDeque, C++ std::deque. A deque can act as both a stack and a queue, and it is the backbone of the monotonic queue.

Priority Queue

Each element has a priority; pop returns the highest (or lowest) priority element. Usually implemented with a binary heap: insert and pop O(log n), peek O(1). Covered in depth in heaps and tries.

Monotonic Stack

A stack kept in increasing or decreasing order. When a new element breaks the order, pop until it fits. Each element is pushed and popped once, so O(n) total.

Next greater element

def next_greater(a):
    res = [-1] * len(a)
    stack = []  # indices, values decreasing
    for i, x in enumerate(a):
        while stack and a[stack[-1]] < x:
            res[stack.pop()] = x
        stack.append(i)
    return res

Classic uses:

ProblemStack order
Next greater elementDecreasing
Next smaller elementIncreasing
Daily temperaturesDecreasing
Largest rectangle in histogramIncreasing
Trapping rain waterDecreasing (or two pointers)
Stock spanDecreasing

Monotonic Queue

A deque that keeps elements in decreasing order to answer sliding window maximum in O(n).

from collections import deque
 
def max_sliding_window(a, k):
    dq, out = deque(), []
    for i, x in enumerate(a):
        while dq and a[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(a[dq[0]])
    return out

The front of the deque is always the max of the current window. A heap would give O(n log k).

Postfix Expression

Infix 3 + 4 * 2 needs precedence rules. Postfix (Reverse Polish Notation) 3 4 2 * + does not.

Evaluating postfix

Scan left to right: push numbers; on an operator, pop two operands, apply, push the result.

3 4 2 * +
push 3, push 4, push 2
* : pop 2, 4, push 8
+ : pop 8, 3, push 11

Infix to postfix (Shunting-yard)

Use an operator stack. Output operands directly. For an operator, pop operators of higher or equal precedence (left-associative) to output, then push. On ), pop until (. At the end, pop everything.

Prefix (Polish) notation + 3 * 4 2 is evaluated right to left the same way.

Pitfalls

  • Popping from an empty stack: always check before pop.
  • Using a list as a queue in Python (pop(0) is O(n)).
  • In monotonic problems, deciding whether to store values or indices: store indices when you need distances or window bounds.
  • Strict vs non-strict comparison changes how duplicates are handled.

Quick revision

  • Stack is LIFO, queue is FIFO, both O(1) per operation.
  • Queue from two stacks is O(1) amortized.
  • Circular queue wraps indices with modulo; track size to tell full from empty.
  • Deque supports both ends; use it for BFS and monotonic queues.
  • Monotonic stack: next greater or smaller element, histogram, temperatures in O(n).
  • Monotonic queue: sliding window max in O(n).
  • Postfix evaluation uses a stack; Shunting-yard converts infix to postfix.