Skip to main content

Exercise 5: Balanced Brackets

Given a string that contains only the characters ( ) [ and ], determine whether the input string contains no unmatched brackets.

Brackets are said to match if every opening bracket has its closing complement subsequent in the string. The string is said to have balanced brackets if all brackets are matched and any subset of brackets enclosed within a matched pair of brackets is also a matched pair of brackets.

Return true if the bracket string is balanced, and false otherwise.

Input: '()[]'
Output: true

Input: '([])'
Output: true

Input: '[(])'
Output: false

Sketch:

Script: