Drill

ProblemsTypeScript › patterns

Balanced delimiters

easypatternsStacksStringsTypeScript

A config linter walks a snippet and rejects it if the brackets, braces and parentheses do not nest cleanly.

balancedDelimiters(text: string) → bool

Solve it in the editor →

Where you start

function balancedDelimiters(text: string): boolean {
  
}

Worked examples

CallResult
balancedDelimiters("()")true
balancedDelimiters("([])")true
balancedDelimiters("(]")false
balancedDelimiters("[(])")false

Hint

Push each opener, and when a closer arrives the top of the stack must be its matching opener.

Reference solution in TypeScript
function balancedDelimiters(text: string): boolean {
  const expect: string[] = [];
  for (const ch of text) {
    if (ch === '(') expect.push(')');
    else if (ch === '[') expect.push(']');
    else if (ch === '{') expect.push('}');
    else if (ch === ')' || ch === ']' || ch === '}') {
      if (expect.pop() !== ch) return false;
    }
  }
  return expect.length === 0;
}

The same problem in another language

More patterns problems in TypeScript