Stack

Linear Helpers

Signal

Matching/balance/nesting, undo last

Template

Push openers, pop and verify on closers.

Worked example (1)

#8

Stack

Stack

Given a string of brackets ()[]{}, decide whether they are correctly matched and nested.

function isValid(s: string): boolean {
  const match: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
  const stack: string[] = [];
  for (const c of s) {
    if (c === '(' || c === '[' || c === '{') stack.push(c);
    else if (stack.pop() !== match[c]) return false;
  }
  return stack.length === 0;
}
Insight

Most-recent-must-close-first is the definition of LIFO.