The balanced brackets problem is fundamental in validating nested structures in programming languages and markup documents, ensuring correct syntax and hierarchy. It is widely used in compilers, interpreters, and data structure manipulation to detect structural errors efficiently.
The Problem: Given a string consisting of a sequence of characters from: `{`, `}`, `[`, `]`, `(`, and `)`, determine if the brackets in the sequence are balanced or not.
A sequence of brackets is considered balanced if: every opening bracket has a corresponding closing bracket in the correct order of nesting.
Some example strings and their status as either balanced or not balanced is given below.
"{([])}{}" is balanced
"{{[[(())]]}}" is balanced
"([{}])" is balanced
"" (empty string) is balanced
"([)]" is not balanced
"()]" is not balanced
"{([)]}" is not balanced
At this point: attempt to solve this problem without looking at the following method. You'll notice that it becomes complicated to solve by scaning the list in the usual manner.
A stack is a data structure that follows the Last In, First Out (LIFO) principle, meaning the last item added is the first one removed. Think of it like stacking plates: you add a new plate on top, and when you take one off, you remove the topmost plate first.
In Python, a list can easily function as a stack. By using the append()
method, we add items to the end of the list (the top of the stack). The pop()
method removes the last item added, making it perfect for implementing stack behavior.
The gist of the method is this: scan the input one bracket at a time. If an opening bracket is encountered, push it into the stack. If a closing bracket is encountered, check the bracket added last (at the top of the stack); if the opening and closing brackets match, remove the opening bracket and continue to the next bracket in the input. In case of a mismatch, report imbalance. At the end, the stack should be empty. Figures 1 and 2 show this method in action for balanced and non-balanced inputs, respectively.
Example with balanced brackets:
Examples with non balanced brackets:
Following is a more detailed description of the algorithm:
(
, {
, or [
, push it into the stack.)
, }
, or ]
, check two things:
False
(there’s no matching opening bracket).False
.True
. If there’s anything left in the stack, return False
.Implement the algorithm from Figure 3 in the following function stub:
Use the following main to test your function: