Welcome to this comprehensive guide on checking balanced parentheses, a fundamental concept in data structures and algorithms! š
This lesson is designed for both beginners and intermediates, focusing on explaining the "why" as well as the "how" of balanced parentheses. Let's dive right in!
Parentheses, also known as brackets, are symbols used in mathematics and programming to group expressions. There are three types of parentheses: (, ), [, ], and {, }.
In this lesson, we will focus on the first two types: (, ).
A string of parentheses is said to be balanced if each opening parenthesis ( has a corresponding closing parenthesis ). If not, the string is unbalanced.
For example:
(), (()), and (((())))) are balanced.()(, ())(, and (())) are unbalanced.To check if a string of parentheses is balanced, we can follow these steps:
(, push it onto the stack.), pop a parenthesis from the stack.Let's check the balance of the following strings:
(())Stack: ()
Closing parenthesis: )
Stack: (
Closing parenthesis: )
Stack: ( // Empty stack, parentheses are balanced.
((()))Stack: (
Closing parenthesis: )
Stack: (
Closing parenthesis: )
Stack: (
Closing parenthesis: )
Stack: ( // Empty stack, parentheses are balanced.
()(()))Stack: (
Closing parenthesis: )
Stack: ( // Not empty, parentheses are unbalanced.
Now, let's write a simple Python function that checks if a given string of parentheses is balanced.
def is_balanced(parentheses):
stack = []
for paren in parentheses:
if paren == '(':
stack.append(paren)
elif paren == ')':
if stack and stack.pop() == '(':
continue
else:
return False
return not stack # Return True if the stack is empty, False otherwise.What does the `is_balanced` function return if the input is a balanced string of parentheses?
Congratulations! You've now learned how to check if a string of parentheses is balanced. This is a fundamental concept in data structures and algorithms that is crucial for understanding more complex topics like parsing and compilers.
Keep practicing and soon, you'll be able to master even more advanced concepts! š”šÆ