Field note / fundamentals

publishedupdated 2026-05-04#algorithms#stack#queue#recursion#bfs

Algorithms Practice: Stack, Queue, and Recursion

The interview patterns behind balanced brackets, monotonic stacks, BFS queues, and recursive decomposition.

TL;DR

  • I reach for a stack when the problem wants reversal, nesting, or “most recent unmatched state.”
  • I reach for a queue when the problem wants breadth-first exploration.
  • I reach for recursion when the problem naturally decomposes into the same smaller problem.
  • The real skill is recognizing structure, not memorizing a long list of named problems.

Context

These are some of the cleanest foundational patterns in interview prep because they show how data structure choice shapes control flow. They also translate well into real engineering work, especially parsing, traversal, and scheduling problems.

The Approach

Balanced brackets is the classic stack warm-up:

function isValidBrackets(value: string): boolean {
  const pairs = new Map([
    [")", "("],
    ["]", "["],
    ["}", "{"],
  ])

  const stack: string[] = []

  for (const char of value) {
    if (!pairs.has(char)) {
      stack.push(char)
      continue
    }

    if (stack.pop() !== pairs.get(char)) {
      return false
    }
  }

  return stack.length === 0
}

Breadth-first traversal is the queue counterpart:

function bfs(graph: Record<string, string[]>, start: string): string[] {
  const visited = new Set([start])
  const queue = [start]
  const order: string[] = []

  while (queue.length > 0) {
    const node = queue.shift()!
    order.push(node)

    for (const neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor)
        queue.push(neighbor)
      }
    }
  }

  return order
}

Trade-offs

  • Recursion is expressive, but call-stack limits still matter.
  • Queues built with shift() are simple in interviews, but I would optimize the implementation in performance-sensitive code.
  • Monotonic stacks are powerful, but only after I clearly see the “next greater/smaller” shape in the problem.

References