Balanced BracketsLoading saved progress…

Balanced Brackets

Implement arrayBalancedBrackets(str) — return whether the brackets in str are properly opened and closed in the correct order. This is the classic Valid Parentheses problem, extended to three bracket types: (), [], and {}. A string is balanced when every opener has a matching closer of the same type, every closer appears in the right order, and nothing is left open at the end. Any character that isn't a bracket is ignored, so it works on real code-like strings.

Signature

// str: string  — a string that may contain (), [], {} and any other characters.
// returns: boolean
//   true if every bracket is matched and correctly nested; false otherwise.
function arrayBalancedBrackets(str): boolean;

Examples

// A nested mix of all three types, each closed in the right order.
arrayBalancedBrackets('([]{})');
// → true
// The ) closes before the [ does — the nesting crosses over.
arrayBalancedBrackets('([)]');
// → false

Notes

  • Same type must match. A ( can only be closed by a ), never by a ] or }. So '(]' is not balanced.
  • Order matters. Brackets must be closed in the reverse of the order they were opened. '([)]' is false because the ( is still open when ) arrives.
  • Nothing left open. Every opener needs a closer. '(((' is false; '' (no brackets at all) is true.
  • A stray closer fails. A closer with no matching opener before it, like ')', is not balanced.
  • Non-bracket characters are ignored. 'a(b)c' is true — only the brackets are checked.
Loading editor…