Search⌘ K

Determine if Brackets are Balanced

Explore how to determine if a string containing brackets is balanced by implementing a stack data structure in Python. Understand the algorithm to match opening and closing brackets, handle special edge cases, and write functions to verify balanced brackets. This lesson builds foundational knowledge in stack operations and prepares you to solve related coding problems efficiently.

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.
  • If we encounter a closing bracket, pop off an element from the stack and
...