R
Rishtaara
Data Structures & Algorithms
Lesson 4 of 8Article16 min

Stacks and Queues in Practice

Stacks and Queues in Practice

Choosing stack vs queue

  • Stack (LIFO): function calls, undo, expression parsing.
  • Queue (FIFO): scheduling, buffering, BFS traversal.
  • Use arrays for quick implementation, linked lists for strict O(1) ends.

Balanced brackets using stack

Parentheses validator
function isBalanced(expr: string): boolean {
  const stack: string[] = [];
  const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };

  for (const ch of expr) {
    if (["(", "[", "{"].includes(ch)) stack.push(ch);
    else if (pairs[ch]) {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }

  return stack.length === 0;
}