Determine if Brackets are Balanced
This lesson will teach us how to determine whether or not a string has balanced usage of brackets by using a stack.
We'll cover the following...
In this lesson, we’re going to determine whether or not a set of brackets are balanced or not by making use of the stack data structure that we defined in the previous lesson.
Let’s first understand what a balanced set of brackets looks like.
A balanced set of brackets is one where the number and type of opening and closing brackets match and that is also properly nested within the string of brackets.
Examples of Balanced Brackets
- { }
- { } { }
- ( ( { [ ] } ) )
Examples of Unbalanced Brackets
- ( ( )
- { { { ) } ]
- [ ] [ ] ] ]
Algorithm
Check out the slides below to have a look at the approach we’ll use to solve this problem:
As shown above, our algorithm is as follows:
- We iterate through the characters of the string.
- If we get an opening bracket, push it onto the stack.
Access this course and 1400+ top-rated courses and projects.