Skip to content

Custom Brackets

01 · Question

Given a string and a list of two-character bracket pairs, return whether its brackets are balanced. Each pair defines an opening character followed by its closer; no character is repeated anywhere in the pair list. Non-bracket characters are ignored. Matching pairs must be properly nested.

Examples: (a+[b]) with ["()", "[]"] → true; ([)] with those pairs → false; )( with [")("] → true; hello with an empty pair list → true.

02 · Analysis

Push the expected closing character whenever an opener appears. For a closer, reject if the stack is empty or the top differs; otherwise pop. At the end require an empty stack.

Trace for ([)]: push ), push ], then reject ) because ] is expected first. Counting brackets cannot detect this crossing. O(n + b) expected time and O(n + b) space, with n input characters and b bracket pairs, using hash maps/sets. Go uses runes to support non-ASCII bracket characters.

03 · Solution

Reference solution

1def balanced_brackets(s, brackets):
2 pairs = {pair[0]: pair[1] for pair in brackets}
3 closers = set(pairs.values())
4 expected = []
5 for char in s:
6 if char in pairs:
7 expected.append(pairs[char])
8 elif char in closers:
9 if not expected or expected[-1] != char:
10 return False
11 expected.pop()
12 return not expected