Check Balanced Parentheses šŸŽÆ

beginner
23 min

Check Balanced Parentheses šŸŽÆ

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!

Understanding Parentheses šŸ’”

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: (, ).

Balanced Parentheses: What's the Fuss? šŸ’”

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.

Checking Balanced Parentheses: A Step-by-Step Approach šŸ’”

To check if a string of parentheses is balanced, we can follow these steps:

  1. Initialize an empty stack.
  2. Iterate through the string from left to right.
  3. For each opening parenthesis (, push it onto the stack.
  4. For each closing parenthesis ), pop a parenthesis from the stack.
  5. If the stack is empty at the end, the parentheses are balanced. Otherwise, they are unbalanced.

Example: Checking Balanced Parentheses šŸ’”

Let's check the balance of the following strings:

  1. (())
Stack: () Closing parenthesis: ) Stack: ( Closing parenthesis: ) Stack: ( // Empty stack, parentheses are balanced.
  1. ((()))
Stack: ( Closing parenthesis: ) Stack: ( Closing parenthesis: ) Stack: ( Closing parenthesis: ) Stack: ( // Empty stack, parentheses are balanced.
  1. ()(()))
Stack: ( Closing parenthesis: ) Stack: ( // Not empty, parentheses are unbalanced.

Implementing the Balanced Parentheses Checker āœ…

Now, let's write a simple Python function that checks if a given string of parentheses is balanced.

python
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.
Quick Quiz
Question 1 of 1

What does the `is_balanced` function return if the input is a balanced string of parentheses?

Wrapping Up šŸ“

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! šŸ’”šŸŽÆ